using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Threading;
using System.Web.Services.Description;
using System.Web.Services.Protocols;
using System.Windows.Forms;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.Runtime;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Xml.Xsl;
using OpenComposite.Base;
using OpenComposite.HumanActivity.Contracts.Participants;
using OpenComposite.Base.Structures;
using OpenComposite.Mapper;
using OpenComposite.EII.Designer.Workflow;
using OpenComposite.Repository.Properties;
using OpenComposite.EII.Repository;
using OpenComposite.Workflow;
using OpenComposite.Workflow.Services;
using OpenComposite.Forms;
using System.Messaging;
using System.Runtime.Serialization.Formatters;
using OpenComposite.HumanActivity.Contracts;
using System.Linq;

namespace OpenComposite.EII.CodeGenerators
{
	/// <summary>
	/// Generate code for workflow deployment.
	/// </summary>
	internal partial class Deployment
	{
		#region Initialization
		/// <summary>
		/// Initializes a new instance of the <see cref="Deployment"/> class.
		/// </summary>
		/// <param name="serviceProvider">The service provider.</param>
		public Deployment(IServiceProvider serviceProvider)
		{
			_serviceProvider = serviceProvider;
		}
		#endregion

		#region Internal Members

		#region Constants for Code Generation
		/// <summary>
		/// Value: ""
		/// </summary>
		internal const string cBObjPropSuffix = ""; // suffix for Business Object properties in Code Beside
		/// <summary>
		/// Value: "Invoke" 
		/// </summary>
		internal const string cServiceCallPrefix = "Invoke";
		/// <summary>
		/// Value: "Contract"
		/// </summary>
		internal const string cContractNamespaceSuffix = "Contract";
		/// <summary>
		/// Value: "_orchestration"
		/// </summary>
		internal const string cOrchestrationField = "_orchestration";
		/// <summary>
		/// Value: "http://www.OpenComposite.com/canonical_document"
		/// </summary>
		internal const string cCanonicalNamespace = "http://www.OpenComposite.com/canonical_document";
		/// <summary>
		/// Value: "Event"
		/// </summary>
		internal const string cEvent = "Event";
		/// <summary>
		/// Value: "EventArgs"
		/// </summary>
		internal const string cEventArgs = "EventArgs";
		/// <summary>
		/// Value: "EventHandler"
		/// </summary>
		internal const string cEventHandler = "EventHandler";
		/// <summary>
		/// Value: "ExternalDataEventArgs"
		/// </summary>
		internal const string cExternalDataEventArgs = "ExternalDataEventArgs";
		/// <summary>
		/// Value: "_Start"
		/// </summary>
		internal const string c_Start = "_Start";
		/// <summary>
		/// Value: "_Reply"
		/// </summary>
		internal const string c_Reply = "_Reply";
		/// <summary>
		/// Value: "Raise"
		/// </summary>
		internal const string cRaise = "Raise";
		/// <summary>
		/// Value: "workflowInstanceId"
		/// </summary>
		internal const string cWorkflowInstanceId = "workflowInstanceId";
		/// <summary>
		/// Value: "input"
		/// </summary>
		internal const string cInput = "input";
		/// <summary>
		/// Value: "methodInput"
		/// </summary>
		internal const string cMethodInput = "methodInput";
		/// <summary>
		/// Value: "_methodInput"
		/// </summary>
		internal const string c_MethodInput = "_methodInput";
		/// <summary>
		/// Value: "MethodInput"
		/// </summary>
		internal const string cPropMethodInput = "MethodInput";
		/// <summary>
		/// Value: "_methodOutput"
		/// </summary>
		internal const string c_MethodOutput = "_methodOutput";
		/// <summary>
		/// Value: "methodOutput"
		/// </summary>
		internal const string cMethodOutput = "methodOutput";
		/// <summary>
		/// Value: "MethodOutput"
		/// </summary>
		internal const string cPropMethodOutput = "MethodOutput";
		/// <summary>
		/// Value: "ReturnValue"
		/// </summary>
		internal const string cReturnValue = "ReturnValue";
		/// <summary>
		/// Value: "instanceId"
		/// </summary>
		internal const string cInstanceId = "instanceId";
		/// <summary>
		/// Value: "_instanceId"
		/// </summary>
		internal const string c_InstanceId = "_instanceId";
		/// <summary>
		/// Value: "InstanceId"
		/// </summary>
		internal const string cPropInstanceId = "InstanceId";
		/// <summary>
		/// Value: "Proxy"
		/// </summary>
		internal const string cProxy = "Proxy";

		/// <summary>
		/// Value: "OpenComposite"
		/// </summary>
		internal const string cOpenComposite = "OpenComposite";
		/// <summary>
		/// Value: "Generated"
		/// </summary>
		internal const string cGenerated = "Generated";
		/// <summary>
		/// Value: "_wfRuntime"
		/// </summary>
		internal const string c_wfRuntime = "_wfRuntime";
		/// <summary>
		/// Value: "_wfInstance"
		/// </summary>
		internal const string c_wfInstance = "_wfInstance";
		/// <summary>
		/// Value: "AddService"
		/// </summary>
		internal const string cAddService = "AddService";
		/// <summary>
		/// Value: "extdatasvc"
		/// </summary>
		internal const string cExtDataSvc = "extdatasvc";
		/// <summary>
		/// Value: "StartRuntime"
		/// </summary>
		internal const string cStartRuntime = "StartRuntime";
		/// <summary>
		/// Value: "StopRuntime"
		/// </summary>
		internal const string cStopRuntime = "StopRuntime";
		/// <summary>
		/// Value: "CreateWorkflow"
		/// </summary>
		internal const string cCreateWorkflow = "CreateWorkflow";
		/// <summary>
		/// Value: "Runtime"
		/// </summary>
		internal const string cRuntime = "Runtime";
		/// <summary>
		/// Value: "Dispose"
		/// </summary>
		internal const string cDispose = "Dispose";
		/// <summary>
		/// Value: "Start"
		/// </summary>
		internal const string cStart = "Start";

		/// <summary>
		/// Value: "_wait";
		/// </summary>
		internal const string c_wait = "_wait";
		/// <summary>
		/// Value: "_outputWS";
		/// </summary>
		internal const string c_outputWS = "_outputWS";
		/// <summary>
		/// Value: "client_{0}Completed"
		/// </summary>
		internal const string cClientXCompleted = "client_{0}Completed";
		/// <summary>
		/// Value: "Async"
		/// </summary>
		internal const string cAsync = "Async";
		/// <summary>
		/// Value: "Completed"
		/// </summary>
		internal const string cCompleted = "Completed";
		/// <summary>
		/// Value: "CompletedEventHandler"
		/// </summary>
		internal const string cCompletedEventHandler = "CompletedEventHandler";
		/// <summary>
		/// Value: "CompletedEventArgs"
		/// </summary>
		internal const string cCompletedEventArgs = "CompletedEventArgs";

		/// <summary>
		/// Value: "Generate Workflow"
		/// </summary>
		internal const string cTaskListSourceNameGenerate = "Generate Workflow";
		/// <summary>
		/// VAlue: "Save Workflow"
		/// </summary>
		internal const string cTaskListSourceNameSave = "Save Workflow";

		/// <summary>
		/// Value: "xsltInputSubscription"
		/// </summary>
		internal const string cxsltInputSubscription = "xsltInputSubscription";
		/// <summary>
		/// Value: "AppSettings"
		/// </summary>
		internal const string cAppSettings = "AppSettings";
		/// <summary>
		/// Value: "xsltInput"
		/// </summary>
		internal const string cxsltInput = "xsltInput";
		/// <summary>
		/// Value: "xsltOutput"
		/// </summary>
		internal const string cxsltOutput = "xsltOutput";

		/// <summary>
		/// Value: "http://schemas.microsoft.com/developer/msbuild/2003"
		/// </summary>
		internal const string cVSProjectFileXmlns = "http://schemas.microsoft.com/developer/msbuild/2003";

		/// <summary>
		/// Value: "sendQueue"
		/// </summary>
		internal const string cSendQueueName = "sendQueue";
		/// <summary>
		/// Value: "receiveQueue"
		/// </summary>
		internal const string cReceiveQueueName = "receiveQueue";
		#endregion

		#region Properties
		private static string[] _refAsms = null;
		internal static string[] DefaultReferencedAssemblies
		{
			get
			{
				if ( _refAsms == null ) {
					_refAsms = new string[] {
						typeof(System.EventHandler).Assembly.Location,
						typeof(System.ComponentModel.AttributeCollection).Assembly.Location,
						typeof(System.Workflow.ComponentModel.CompositeActivity).Assembly.Location,
						typeof(System.Workflow.Activities.SequentialWorkflowActivity).Assembly.Location,
						typeof(OpenComposite.Workflow.LogicalEPActivity).Assembly.Location,
						typeof(System.Runtime.Serialization.XsdDataContractImporter).Assembly.Location,
						typeof(System.ServiceModel.EndpointAddress).Assembly.Location,
						typeof(System.Web.Services.WebService).Assembly.Location,
						typeof(System.Xml.XmlDocument).Assembly.Location,
						typeof(System.Configuration.ConfigurationManager).Assembly.Location,
						typeof(OpenComposite.Base.Structures.RepositoryInformationAttribute).Assembly.Location,
						typeof(System.Configuration.ConfigurationManager).Assembly.Location
					};
				}
				return _refAsms;
			}
		}
		#endregion

		#region Methods

		#region Deploy Workflow
		/// <summary>
		/// Deploys the workflow.
		/// </summary>
		/// <param name="path">The path.</param>
		/// <param name="workflow">The workflow.</param>
		/// <param name="update">if set to <c>true</c> [update].</param>
		internal void DeployWorkflow(string path, Repository.Workflow workflow, bool update)
		{
			if ( workflow == null )
				throw new ArgumentNullException("workflow");
			if ( string.IsNullOrEmpty(workflow.CodeLogicalActivity) )
				throw new Exception(
					string.Format("Orchestration \"{0}\" not available. You need to create and save the orchestration before deploy the composite.",
						workflow.Name));

			// create project directory
			string sourcepath = Path.Combine(Application.StartupPath, @"Templates\Orchestration");
			string targetpath;
			if ( path.EndsWith(workflow.Name) )
				targetpath = path;
			else
				targetpath = Path.Combine(path, workflow.Name);

			if ( !Directory.Exists(targetpath) )
				Directory.CreateDirectory(targetpath);

			workflow.Path = targetpath;
			workflow.Save();

			if ( workflow.BuildType == WorkflowBuildType.ASMX_IIS ) {
				this.deployASMX_IIS(sourcepath, targetpath, workflow, update);
			} else if ( workflow.BuildType == WorkflowBuildType.WCF_WindowsForm ) {
				this.deployMashup_WinForm(sourcepath, targetpath, workflow, update);
			} else {
				this.deployWCF_IIS(sourcepath, targetpath, workflow, update);
			}

			// open project
			System.Diagnostics.Process.Start(targetpath);
		}
		#endregion

		#region Service Call

		/// <summary>
		/// Creates the find free port method.
		/// </summary>
		/// <param name="methodName">Name of the method.</param>
		/// <param name="codeClass">The code class.</param>
		internal void CreateFindFreePortMethod(string methodName, CodeTypeDeclaration codeClass)
		{
			CodeMemberMethod methfindFreePort = new CodeMemberMethod();
			methfindFreePort.Attributes = MemberAttributes.Private | MemberAttributes.Final;
			methfindFreePort.Name = methodName;
			methfindFreePort.ReturnType = new CodeTypeReference(typeof(int));
			methfindFreePort.Statements.Add(
				new CodeVariableDeclarationStatement(typeof(IPEndPoint), "endpoint",
					new CodeObjectCreateExpression(typeof(IPEndPoint),
						new CodeFieldReferenceExpression(
							new CodeTypeReferenceExpression(typeof(IPAddress)), "Any"),
						new CodePrimitiveExpression(0))));
			methfindFreePort.Statements.Add(
				new CodeVariableDeclarationStatement(typeof(Socket), "socket",
					new CodeObjectCreateExpression(typeof(Socket),
						new CodeFieldReferenceExpression(
							new CodeTypeReferenceExpression(typeof(AddressFamily)), "InterNetwork"),
						new CodeFieldReferenceExpression(
							new CodeTypeReferenceExpression(typeof(SocketType)), "Stream"),
						new CodeFieldReferenceExpression(
							new CodeTypeReferenceExpression(typeof(ProtocolType)), "Tcp"))));
			CodeTryCatchFinallyStatement tryfinalSocket = new CodeTryCatchFinallyStatement();
			tryfinalSocket.TryStatements.Add(
				new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("socket"), "Bind",
					new CodeVariableReferenceExpression("endpoint")));
			tryfinalSocket.TryStatements.Add(
				new CodeVariableDeclarationStatement(typeof(IPEndPoint), "local",
					new CodeCastExpression(typeof(IPEndPoint),
						new CodePropertyReferenceExpression(
							new CodeVariableReferenceExpression("socket"), "LocalEndPoint"))));
			tryfinalSocket.TryStatements.Add(
				new CodeMethodReturnStatement(
					new CodePropertyReferenceExpression(
						new CodeVariableReferenceExpression("local"), "Port")));
			tryfinalSocket.FinallyStatements.Add(
				new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("socket"), "Close"));
			methfindFreePort.Statements.Add(tryfinalSocket);
			codeClass.Members.Add(methfindFreePort);
		}

		/// <summary>
		/// Generates the service calls.
		/// </summary>
		/// <param name="codeServices">The code services.</param>
		/// <param name="ctdServices">The CTD services.</param>
		/// <param name="codeContracts">The code contracts.</param>
		/// <param name="codeRules">The code rules.</param>
		/// <param name="currentSvcGenType">Type of the current SVC gen.</param>
		/// <param name="typeProvider">The type provider.</param>
		/// <param name="typeRefLogActContract">The type ref log act contract.</param>
		/// <param name="logactname">The logactname.</param>
		/// <param name="useServiceCallPrefix">if set to <c>true</c> [use service call prefix].</param>
		/// <param name="webmeth">The webmeth.</param>
		/// <param name="wmCallback">The wm callback.</param>
		/// <param name="websvc">The websvc.</param>
		/// <param name="msmq">The MSMQ.</param>
		/// <param name="logact">The logact.</param>
		/// <param name="logcap">The logcap.</param>
		/// <param name="contractnspace">The contractnspace.</param>
		/// <param name="methInMap">The meth in map.</param>
		/// <param name="methOutMap">The meth out map.</param>
		/// <param name="methContract">The meth contract.</param>
		/// <param name="typeRefMapClass">The type ref map class.</param>
		/// <param name="typeRefOutput">The type ref output.</param>
		/// <param name="typeRefInput">The type ref input.</param>
		/// <param name="listTypeRefInputLogAct">The list type ref input log act.</param>
		/// <param name="bindings">The bindings.</param>
		/// <param name="endpointConfigName">Name of the endpoint config.</param>
		/// <param name="namespaceData">The namespace data.</param>
		/// <param name="namespaceRules">The namespace rules.</param>
		/// <param name="generateStub">if set to <c>true</c> [generate stub].</param>
		internal void GenerateServiceCalls(
			CodeCompileUnit codeServices, CodeTypeDeclaration ctdServices, CodeCompileUnit codeContracts,
			CodeCompileUnit codeRules,
			ServiceGenerationType currentSvcGenType,
			TypeProvider typeProvider,
			CodeTypeReference typeRefLogActContract,
			string logactname, bool useServiceCallPrefix,
			Repository.WebMethod webmeth, Repository.WebMethod wmCallback, Repository.WebService websvc, Repository.MessageQueueEx sendMsmq, Repository.MessageQueueEx receiveMsmq,
			Repository.LogicalActivity logact, LogicalCapabilityActivity logcap,
			string contractnspace,
			CodeMemberMethod methInMap, CodeMemberMethod methOutMap, CodeMemberMethod methContract,
			CodeTypeReference typeRefMapClass, CodeTypeReference typeRefOutput,
			CodeTypeReference typeRefInput, List<CodeTypeReference> listTypeRefInputLogAct,
			Collection<System.ServiceModel.Channels.Binding> bindings, string endpointConfigName,
			string namespaceData, string namespaceRules, bool generateStub)
		{
			GenerateServiceCalls(codeServices, ctdServices, codeContracts, codeRules, currentSvcGenType, typeProvider,
				typeRefLogActContract, logactname, useServiceCallPrefix, webmeth, wmCallback, websvc, sendMsmq, receiveMsmq, logact,
				logcap, contractnspace, methInMap, methOutMap, methContract, typeRefMapClass, typeRefOutput,
				typeRefInput, listTypeRefInputLogAct, bindings, endpointConfigName, namespaceData, namespaceRules,
				false, generateStub);
		}

		/// <summary>
		/// Generates the service calls.
		/// </summary>
		/// <param name="codeServices">The code services.</param>
		/// <param name="ctdServices">The CTD services.</param>
		/// <param name="codeContracts">The code contracts.</param>
		/// <param name="codeRules">The code rules.</param>
		/// <param name="currentSvcGenType">Type of the current SVC gen.</param>
		/// <param name="typeProvider">The type provider.</param>
		/// <param name="typeRefLogActContract">The type ref log act contract.</param>
		/// <param name="logactname">The logactname.</param>
		/// <param name="useServiceCallPrefix">if set to <c>true</c> [use service call prefix].</param>
		/// <param name="webmeth">The webmeth.</param>
		/// <param name="wmCallback">The wm callback.</param>
		/// <param name="websvc">The websvc.</param>
		/// <param name="msmq">The MSMQ.</param>
		/// <param name="logact">The logact.</param>
		/// <param name="logcap">The logcap.</param>
		/// <param name="contractnspace">The contractnspace.</param>
		/// <param name="methInMap">The meth in map.</param>
		/// <param name="methOutMap">The meth out map.</param>
		/// <param name="methContract">The meth contract.</param>
		/// <param name="typeRefMapClass">The type ref map class.</param>
		/// <param name="typeRefOutput">The type ref output.</param>
		/// <param name="typeRefInput">The type ref input.</param>
		/// <param name="listTypeRefInputLogAct">The list type ref input log act.</param>
		/// <param name="bindings">The bindings.</param>
		/// <param name="endpointConfigName">Name of the endpoint config.</param>
		/// <param name="namespaceData">The namespace data.</param>
		/// <param name="namespaceRules">The namespace rules.</param>
		/// <param name="standalone">If set to true, the ActivityExecutionContext parameter is omitted.</param>
		/// <param name="generateStub">if set to <c>true</c> [generate stub].</param>
		internal void GenerateServiceCalls(
			CodeCompileUnit codeServices, CodeTypeDeclaration ctdServices, CodeCompileUnit codeContracts,
			CodeCompileUnit codeRules,
			ServiceGenerationType currentSvcGenType,
			TypeProvider typeProvider,
			CodeTypeReference typeRefLogActContract,
			string logactname, bool useServiceCallPrefix,
			Repository.WebMethod webmeth, Repository.WebMethod wmCallback, Repository.WebService websvc, Repository.MessageQueueEx sendMsmq, Repository.MessageQueueEx receiveMsmq,
			Repository.LogicalActivity logact, LogicalCapabilityActivity logcap,
			string contractnspace,
			CodeMemberMethod methInMap, CodeMemberMethod methOutMap, CodeMemberMethod methContract,
			CodeTypeReference typeRefMapClass, CodeTypeReference typeRefOutput,
			CodeTypeReference typeRefInput, List<CodeTypeReference> listTypeRefInputLogAct,
			Collection<System.ServiceModel.Channels.Binding> bindings, string endpointConfigName,
			string namespaceData, string namespaceRules, bool standalone, bool generateStub)
		{
			#region set generateAsyncInvoke
			bool generateAsyncInvoke = logcap is LogicalAsyncStartActivity;
			#endregion
			#region set isWSDualHttpBinding
			bool isWSDualHttpBinding = false;
			if ( bindings != null && bindings.Count > 0 ) {
				if ( bindings[0] is WSDualHttpBinding ) {
					isWSDualHttpBinding = true;
				} else if ( bindings[0] is CustomBinding ) {
					CustomBinding cb = (CustomBinding)bindings[0];
					isWSDualHttpBinding = cb.Elements.Contains(typeof(CompositeDuplexBindingElement)) &&
										  cb.Elements.Contains(typeof(HttpTransportBindingElement));
				}
			}
			#endregion

			#region Get Input / Output Types
			RepositoryService repSvc = (RepositoryService)this.GetService(typeof(RepositoryService));
			Debug.Assert(repSvc != null);
			Dictionary<Type, string> dicTypeNamespace = new Dictionary<Type, string>();
			bool hasInput = false;
			bool hasOutput = false;
			CodeMemberMethod methSvcCall = new CodeMemberMethod();
			if ( useServiceCallPrefix ) {
				methSvcCall.Name = cServiceCallPrefix + logactname;
			} else {
				methSvcCall.Name = logactname;
			}
			methSvcCall.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			// add RepositoryInformationAttribute with logical activity informations
			if ( logact != null ) {
				methSvcCall.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(RepositoryInformationAttribute)),
						new CodeAttributeArgument(new CodePrimitiveExpression(logact.ID)),
						new CodeAttributeArgument(new CodePrimitiveExpression(logact.Name)),
						new CodeAttributeArgument(new CodePrimitiveExpression(logact.RepositoryItemTypeName))));
				if ( currentSvcGenType == ServiceGenerationType.HumanActivityService ) {
					if ( logact.LogicalMethod != null && logact.LogicalMethod.HumanActivity != null ) {
						// add RepositoryInformationAttribute with human activity informations
						methSvcCall.CustomAttributes.Add(
							new CodeAttributeDeclaration(
								new CodeTypeReference(typeof(RepositoryInformationAttribute)),
								new CodeAttributeArgument(new CodePrimitiveExpression(logact.LogicalMethod.HumanActivityID)),
								new CodeAttributeArgument(new CodePrimitiveExpression(logact.LogicalMethod.HumanActivity.Name)),
								new CodeAttributeArgument(new CodePrimitiveExpression(Resources.sHumanActivity))));
					}
				} else {
					// add RepositoryInformationAttribute with web method informations
					if ( webmeth != null ) {
						methSvcCall.CustomAttributes.Add(
							new CodeAttributeDeclaration(
								new CodeTypeReference(typeof(RepositoryInformationAttribute)),
								new CodeAttributeArgument(new CodePrimitiveExpression(webmeth.ID)),
								new CodeAttributeArgument(new CodePrimitiveExpression(webmeth.Name)),
								new CodeAttributeArgument(new CodePrimitiveExpression(webmeth.RepositoryItemTypeName))));
					}
				}
			}
			if ( !standalone ) {
				methSvcCall.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(ActivityExecutionContext), "context"));
			}
			if ( listTypeRefInputLogAct.Count > 0 ) {
				for ( int i = 0; i < listTypeRefInputLogAct.Count; i++ ) {
					methSvcCall.Parameters.Add(
						new CodeParameterDeclarationExpression(listTypeRefInputLogAct[i], "input" + i.ToString()));
				}
				hasInput = true;
			} else if ( typeRefInput != null ) {
				methSvcCall.Parameters.Add(
					new CodeParameterDeclarationExpression(typeRefInput, "input"));
				hasInput = true;
			}
			if ( typeRefOutput != null ) {
				if ( !generateAsyncInvoke ) {
					methSvcCall.ReturnType = typeRefOutput;
				}
				hasOutput = true;
			}
			List<Type> typesWSInput = new List<Type>();
			if ( currentSvcGenType == ServiceGenerationType.SystemWebService ) {
				foreach ( string sType in webmeth.InputTypeName.Split(';') ) {
					string type = sType.Trim();
					string ns = null;
					if ( type.Contains(":") ) {
						ns = type;
						string[] splitType = type.Split(':');
						type = splitType[splitType.Length - 1];
						ns = ns.Remove(ns.Length - type.Length - 1, type.Length + 1);
					}
					if ( type.StartsWith("System.") ) {
						typesWSInput.Add(Type.GetType(type));
					} else {
						Type t = typeProvider.GetType(type);
						if ( t == null ) t = typeProvider.GetType(type + "Request");
						if ( t == null ) t = typeProvider.GetType(contractnspace + "." + type + "Request");
						if ( t == null ) t = typeProvider.GetType(contractnspace + "." + type);
						typesWSInput.Add(t);
						if ( !string.IsNullOrEmpty(ns) ) {
							dicTypeNamespace.Add(t, ns);
						}
					}
				}
			} else if ( currentSvcGenType == ServiceGenerationType.HumanActivityService ) {
				typesWSInput.Add(typeProvider.GetType(contractnspace + "." + webmeth.InputTypeName));
			} else {
				string[] inputTypeNames = null;
				if ( webmeth != null ) inputTypeNames = webmeth.InputTypeName.Split(';');
				else inputTypeNames = new string[] { };
				foreach ( string sType in inputTypeNames ) {
					string type = sType.Trim();
					string ns = null;
					if ( type.Contains(":") ) {
						ns = type;
						string[] splitType = type.Split(':');
						type = splitType[splitType.Length - 1];
						ns = ns.Remove(ns.Length - type.Length - 1, type.Length + 1);
					}
					if ( type.StartsWith("System.") ) {
						typesWSInput.Add(Type.GetType(type));
					} else {
						Type t = typeProvider.GetType(type);
						if ( t == null ) t = typeProvider.GetType(type + "Request");
						if ( t == null ) t = typeProvider.GetType(contractnspace + "." + type + "Request");
						typesWSInput.Add(t);
						if ( !string.IsNullOrEmpty(ns) ) {
							dicTypeNamespace.Add(t, ns);
						}
					}
				}
			}
			List<Type> typesWSOutput = new List<Type>();//OLD: = typeProvider.GetType(meth.OutputTypeName);
			if ( currentSvcGenType == ServiceGenerationType.SystemWebService ) {
				string[] outputTypeNames = null;
				if ( webmeth != null ) outputTypeNames = webmeth.OutputTypeName.Split(';');
				else outputTypeNames = new string[] { "System.Object" };
				foreach ( string sType in outputTypeNames ) {
					string type = sType.Trim();
					string ns = null;
					if ( type.Contains(":") ) {
						ns = type;
						string[] splitType = type.Split(':');
						type = splitType[splitType.Length - 1];
						ns = ns.Remove(ns.Length - type.Length - 1, type.Length + 1);
					}
					if ( type.StartsWith("System.") ) {
						typesWSOutput.Add(Type.GetType(type));
					} else {
						Type t = typeProvider.GetType(contractnspace + "." + type);
						typesWSOutput.Add(t);
						if ( !string.IsNullOrEmpty(ns) && !dicTypeNamespace.ContainsKey(t) ) {
							dicTypeNamespace.Add(t, ns);
						}
					}
				}
			} else if ( currentSvcGenType == ServiceGenerationType.HumanActivityService ) {
				typesWSOutput.Add(typeProvider.GetType(contractnspace + "." + webmeth.OutputTypeName));
			} else if ( currentSvcGenType == ServiceGenerationType.MessageQueueService ) {
				typesWSOutput.Add(typeof(object));
			} else {
				string[] typenames = ( wmCallback != null ?
					wmCallback.OutputTypeName.Split(';') : webmeth.OutputTypeName.Split(';') );
				foreach ( string sType in typenames ) {
					string type = sType.Trim();
					string ns = null;
					if ( type.Contains(":") ) {
						ns = type;
						string[] splitType = type.Split(':');
						type = splitType[splitType.Length - 1];
						ns = ns.Remove(ns.Length - type.Length - 1, type.Length + 1);
					}
					if ( type.StartsWith("System.") ) {
						typesWSOutput.Add(Type.GetType(type));
					} else {
						Type t = typeProvider.GetType(type);
						if ( t == null ) t = typeProvider.GetType(contractnspace + "." + type);
						typesWSOutput.Add(t);
						if ( !string.IsNullOrEmpty(ns) && !dicTypeNamespace.ContainsKey(t) ) {
							dicTypeNamespace.Add(t, ns);
						}
					}
				}
			}
			#endregion

			if ( !generateStub ) {
				#region Declare Variables, Do Mapping and Create Input Object
				bool missingInMap = ( hasInput && methInMap == null );
				bool missingOutMap = ( hasOutput && methOutMap == null );
				if ( missingInMap && missingOutMap )
					throw new Exception("Missing input and output mapping.");
				if ( missingInMap )
					throw new Exception("Missing input mapping.");
				if ( missingOutMap )
					throw new Exception("Missing output mapping.");

				CodeExpression mapoutTargetObj = hasOutput ?
					( methOutMap.Attributes & MemberAttributes.Static ) == MemberAttributes.Static ?
					(CodeExpression)new CodeTypeReferenceExpression(typeRefMapClass) :
					(CodeExpression)new CodePropertyReferenceExpression(
						new CodeFieldReferenceExpression(
							new CodeThisReferenceExpression(), cOrchestrationField),
						"Mapping") : null;

				if ( ( hasInput || /* if msmq is used, allow empty input (codemapping) */
					 ( ( sendMsmq != null || receiveMsmq != null ) && logact.LogicalMethod.InputBusinessObject == null ) ) &&
					 ( logact != null && logact.LogicalMethod.ExtendedProperties.UseInputCodeMapping ) ) {
					CodeExpression mapinTargetObj = null;
					if ( methOutMap != null ) {
						mapinTargetObj =
							( methOutMap.Attributes & MemberAttributes.Static ) == MemberAttributes.Static ?
							(CodeExpression)new CodeTypeReferenceExpression(typeRefMapClass) :
							(CodeExpression)new CodePropertyReferenceExpression(
								new CodeFieldReferenceExpression(
									new CodeThisReferenceExpression(), cOrchestrationField),
								"Mapping");
					} else {
						mapinTargetObj =
							new CodeTypeReferenceExpression(typeRefMapClass);
					}
					List<CodeExpression> parameters = new List<CodeExpression>();
					//for ( int i = 0; i < listTypeRefInputLogAct.Count; i++ ) {
					//    paramters.Add(
					//        new CodeVariableReferenceExpression(
					//            string.Format("input{0}", i)));
					//}
					if ( listTypeRefInputLogAct.Count > 0 ) {
						for ( int i = 0; i < listTypeRefInputLogAct.Count; i++ ) {
							parameters.Add(
								new CodeVariableReferenceExpression(
									string.Format("input{0}", i)));
						}
					} else if ( typeRefInput != null ) {
						parameters.Add(
							new CodeVariableReferenceExpression("input"));
					}
					for ( int i = 0; i < typesWSInput.Count; i++ ) {
						if ( typesWSInput[i].IsValueType ) {
							methSvcCall.Statements.Add(	// PhysicalDocType inputWS = null;
								new CodeVariableDeclarationStatement(
									typesWSInput[i],//typenamesfull[i],
									string.Format("inputWS{0}", i),
									new CodeDefaultValueExpression(
										new CodeTypeReference(typesWSInput[i]))));
						} else {
							methSvcCall.Statements.Add(	// PhysicalDocType inputWS = null;
								new CodeVariableDeclarationStatement(
									typesWSInput[i],//typenamesfull[i],
									string.Format("inputWS{0}", i),
									new CodePrimitiveExpression(null)));
						}
						parameters.Add(
							new CodeDirectionExpression(
								FieldDirection.Out,
								new CodeVariableReferenceExpression(
									string.Format("inputWS{0}", i))));
					}
					if ( sendMsmq != null ) {
						if ( logact.LogicalMethod.SendMessageQueue != null ) {
							parameters.Add(
								new CodeDirectionExpression(
									FieldDirection.Out,
									new CodeVariableReferenceExpression(
										"input")));
							methSvcCall.Statements.Add(
								 new CodeVariableDeclarationStatement(
									 typeof(object),
									 "input",
									 new CodePrimitiveExpression(null)));
						}
					}

					methSvcCall.Statements.Add(
						new CodeMethodInvokeExpression(
							mapinTargetObj,
							methInMap.Name,
							parameters.ToArray()));
				} else if ( hasInput && methInMap != null ) {
					#region XSLT Mapping
					// get variable names
					string[] varnames = webmeth.InputVariableName.Split(';');
					// get and extract typenames
					//string[] typenamesfull = webmeth.InputTypeName.Split(';');
					//List<string> typenames = new List<string>();
					//foreach ( string typenm in typenamesfull ) {
					//    string[] tmp = typenm.Split('.');
					//    if ( tmp != null && tmp.Length > 0 )
					//        typenames.Add(tmp[tmp.Length - 1]);
					//}
					// do input mapping
					List<CodeExpression> listMapParams = new List<CodeExpression>();
					if ( listTypeRefInputLogAct.Count > 0 ) {
						for ( int i = 0; i < listTypeRefInputLogAct.Count; i++ ) {
							listMapParams.Add(new CodeArgumentReferenceExpression("input" + i.ToString()));
						}
					} else {
						listMapParams.Add(new CodeArgumentReferenceExpression("input"));
					}
					CodeExpression mappingTargetObj =
						( methInMap.Attributes & MemberAttributes.Static ) == MemberAttributes.Static ?
						(CodeExpression)new CodeTypeReferenceExpression(typeRefMapClass) :
						(CodeExpression)new CodePropertyReferenceExpression(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), cOrchestrationField),
							"Mapping");
					methSvcCall.Statements.Add( // XmlDocument xdIn = Mapping.ActInputMapping(input);
						new CodeVariableDeclarationStatement(
							typeof(XmlDocument),
							"xdIn",
							new CodeMethodInvokeExpression(
								mappingTargetObj,
								methInMap.Name,
								listMapParams.ToArray())));
					// XmlNamespaceManager xmgr = new XmlNamespanceManager(xdIn.NameTable);
					methSvcCall.Statements.Add(
						new CodeVariableDeclarationStatement(
							typeof(XmlNamespaceManager),
							"xmgr",
							new CodeObjectCreateExpression(
								typeof(XmlNamespaceManager),
								new CodePropertyReferenceExpression(
									new CodeVariableReferenceExpression("xdIn"),
									"NameTable"))));
					// xmgr.AddNamespace(xdIn.DocumentElement.Prefix, xdIn.DocumentElement.NamespaceURI);
					methSvcCall.Statements.Add(
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("xmgr"),
							"AddNamespace",
							new CodePropertyReferenceExpression(
								new CodePropertyReferenceExpression(
									new CodeVariableReferenceExpression("xdIn"),
									"DocumentElement"),
								"Prefix"),
							new CodePropertyReferenceExpression(
								new CodePropertyReferenceExpression(
									new CodeVariableReferenceExpression("xdIn"),
									"DocumentElement"),
								"NamespaceURI")));
					for ( int i = 0; i < typesWSInput.Count; i++ ) {
						if ( typesWSInput[i].IsValueType ) {
							methSvcCall.Statements.Add(	// PhysicalDocType inputWS = null;
								new CodeVariableDeclarationStatement(
									typesWSInput[i],//typenamesfull[i],
									"inputWS" + i.ToString(),
									new CodeDefaultValueExpression(new CodeTypeReference(typesWSInput[i]))));
						} else {
							methSvcCall.Statements.Add(	// PhysicalDocType inputWS = null;
								new CodeVariableDeclarationStatement(
									typesWSInput[i],//typenamesfull[i],
									"inputWS" + i.ToString(),
									new CodePrimitiveExpression(null)));
						}
						// XmlNode xn0 = xdIn.SelectSingleNode(
						//    string.Format("//{0}:{1}", xdIn.DocumentElement.Prefix, typenames[i]), xmgr);
						methSvcCall.Statements.Add(
							new CodeVariableDeclarationStatement(
								typeof(XmlNode),
								"xn" + i.ToString(),
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("xdIn"),
									"SelectSingleNode",
									new CodeMethodInvokeExpression(
										new CodeTypeReferenceExpression(typeof(string)),
										"Format",
										new CodePrimitiveExpression("//{0}:{1}"),
										new CodePropertyReferenceExpression(
											new CodePropertyReferenceExpression(
												new CodeVariableReferenceExpression("xdIn"),
												"DocumentElement"),
											"Prefix"),
										new CodePrimitiveExpression(varnames[i])),
									new CodeVariableReferenceExpression("xmgr"))));
						CodeConditionStatement codeIfXnNotNULL = new CodeConditionStatement();
						codeIfXnNotNULL.Condition =
							new CodeBinaryOperatorExpression(
								new CodeVariableReferenceExpression("xn" + i.ToString()),
								CodeBinaryOperatorType.IdentityInequality,
								new CodePrimitiveExpression(null));
						codeIfXnNotNULL.TrueStatements.Add(	// XmlDocument xdInput0 = new XmlDocument();
							new CodeVariableDeclarationStatement(
								typeof(XmlDocument),
								"xdInput" + i.ToString(),
								new CodeObjectCreateExpression(typeof(XmlDocument))));
						//Type tIn = Type.GetType(typenamesfull[i]);
						//if ( tIn != null && tIn.IsPrimitive ) {
						if ( typesWSInput[i] != null && typesWSInput[i].IsPrimitive ) {
							codeIfXnNotNULL.TrueStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("xdInput" + i.ToString()),
									"AppendChild",
									new CodeMethodInvokeExpression(
										new CodeVariableReferenceExpression("xdInput" + i.ToString()),
										"ImportNode",
										new CodeVariableReferenceExpression("xn" + i.ToString()),
										new CodePrimitiveExpression(true))));
						} else {
							// xdInput0.AppendChild(xdInput.CreateElement(xn.Prefix + ":TYPENAME", xn.NamespaceURI));
							if ( dicTypeNamespace.ContainsKey(typesWSInput[i]) ) {
								codeIfXnNotNULL.TrueStatements.Add(
									new CodeMethodInvokeExpression(
										new CodeVariableReferenceExpression("xdInput" + i.ToString()),
										"AppendChild",
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("xdInput" + i.ToString()),
											"CreateElement",
											new CodeBinaryOperatorExpression(
												new CodePrimitiveExpression("tns"),
												CodeBinaryOperatorType.Add,
												new CodePrimitiveExpression(":" + ( currentSvcGenType == ServiceGenerationType.HumanActivityService ? varnames[i] : typesWSInput[i].Name ))),
											new CodePrimitiveExpression(dicTypeNamespace[typesWSInput[i]]))));
							} else {
								string ns = null;
								object[] objs = typesWSInput[i].GetCustomAttributes(typeof(DataContractAttribute), false);
								if ( objs != null && objs.Length > 0 ) {
									AttributeInfoAttribute aia = objs[0] as AttributeInfoAttribute;
									DataContractAttribute dca;
									if ( aia != null ) {
										dca = (DataContractAttribute)aia.AttributeInfo.CreateAttribute();
									} else {
										dca = (DataContractAttribute)objs[0];
									}
									ns = dca.Namespace;
								}
								codeIfXnNotNULL.TrueStatements.Add(
									new CodeMethodInvokeExpression(
										new CodeVariableReferenceExpression("xdInput" + i.ToString()),
										"AppendChild",
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("xdInput" + i.ToString()),
											"CreateElement",
											new CodeBinaryOperatorExpression(
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("xn" + i.ToString()),
													"Prefix"),
												CodeBinaryOperatorType.Add,
												new CodePrimitiveExpression(":" + ( currentSvcGenType == ServiceGenerationType.HumanActivityService ? varnames[i] : typesWSInput[i].Name ))),
											( string.IsNullOrEmpty(ns) ?
												(CodeExpression)new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("xn" + i.ToString()),
													"NamespaceURI") :
												(CodeExpression)new CodePrimitiveExpression(ns) ))));
							}
							codeIfXnNotNULL.TrueStatements.Add(
								new CodeIterationStatement(
									new CodeVariableDeclarationStatement(
										typeof(int), "i", new CodePrimitiveExpression(0)),
									new CodeBinaryOperatorExpression(
										new CodeVariableReferenceExpression("i"),
										CodeBinaryOperatorType.LessThan,
										new CodePropertyReferenceExpression(
											new CodePropertyReferenceExpression(
												new CodeVariableReferenceExpression("xn" + i.ToString()),
												"ChildNodes"),
											"Count")),
									new CodeAssignStatement(
										new CodeVariableReferenceExpression("i"),
										new CodeBinaryOperatorExpression(
											new CodeVariableReferenceExpression("i"),
											CodeBinaryOperatorType.Add,
											new CodePrimitiveExpression(1))),
									new CodeExpressionStatement(new CodeMethodInvokeExpression(
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression("xdInput" + i.ToString()),
											"DocumentElement"),
										"AppendChild",
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("xdInput" + i.ToString()),
											"ImportNode",
											new CodeIndexerExpression(
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("xn" + i.ToString()),
													"ChildNodes"),
												new CodeVariableReferenceExpression("i")),
											new CodePrimitiveExpression(true))))));
						}
						codeIfXnNotNULL.TrueStatements.Add(	// MemoryStream msInput = new MemoryStream();
							new CodeVariableDeclarationStatement(
								typeof(MemoryStream),
								"msInput" + i.ToString(),
								new CodeObjectCreateExpression(typeof(MemoryStream))));
						codeIfXnNotNULL.TrueStatements.Add( // xdInput.Save(msInput);
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("xdInput" + i.ToString()),
								"Save",
								new CodeVariableReferenceExpression("msInput" + i.ToString())));
						codeIfXnNotNULL.TrueStatements.Add(	// msInput.Position = 0;
							new CodeAssignStatement(
								new CodePropertyReferenceExpression(
									new CodeVariableReferenceExpression("msInput" + i.ToString()),
									"Position"),
								new CodePrimitiveExpression(0)));
						codeIfXnNotNULL.TrueStatements.Add(	// object obj0 = null;
							new CodeVariableDeclarationStatement(
								typeof(object),
								"obj" + i.ToString(),
								new CodePrimitiveExpression(null)));
						if ( typesWSInput[i].GetCustomAttributes(typeof(DataContractAttribute), true).Length > 0 ||
							 typesWSInput[i].GetCustomAttributes(typeof(CollectionDataContractAttribute), true).Length > 0 ) {
							// use DataContractSerializer
							// DataContractSerializer dcsInput0 = new DataContractSerializer(INPUTTYPE);
							codeIfXnNotNULL.TrueStatements.Add(
								new CodeVariableDeclarationStatement(
									typeof(DataContractSerializer),
									"dcsInput" + i.ToString(),
									new CodeObjectCreateExpression(
										typeof(DataContractSerializer),
										new CodeTypeOfExpression(typesWSInput[i]))));
							codeIfXnNotNULL.TrueStatements.Add(	// obj0 = dcsInput0.ReadObject(msInput);
								new CodeAssignStatement(
									new CodeVariableReferenceExpression("obj" + i.ToString()),
									new CodeMethodInvokeExpression(
										new CodeVariableReferenceExpression("dcsInput" + i.ToString()),
										"ReadObject",
										new CodeVariableReferenceExpression("msInput" + i.ToString()))));
						} else {
							// use XmlSerialzer
							// XmlRootAttribute root = new XmlRootAttribute(TYPENAME);
							string rootname = (
								( currentSvcGenType == ServiceGenerationType.HumanActivityService || typesWSInput[i].IsPrimitive ) ?
								varnames[i] : typesWSInput[i].Name );
							codeIfXnNotNULL.TrueStatements.Add(
								new CodeVariableDeclarationStatement(
									typeof(XmlRootAttribute),
									"root" + i.ToString(),
									new CodeObjectCreateExpression(
										typeof(XmlRootAttribute),
										new CodePrimitiveExpression(rootname))));
							// root.Namespace = xdInput0.DocumentElement.NamespaceURI;
							codeIfXnNotNULL.TrueStatements.Add(
								new CodeAssignStatement(
									new CodePropertyReferenceExpression(
										new CodeVariableReferenceExpression("root" + i.ToString()),
										"Namespace"),
									new CodePropertyReferenceExpression(
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression("xdInput" + i.ToString()),
											"DocumentElement"),
										"NamespaceURI")));
							// XmlSerializer xsInput0 = new XmlSerializer(typeof(INPUTTYPE), root);
							codeIfXnNotNULL.TrueStatements.Add(
								new CodeVariableDeclarationStatement(
									typeof(XmlSerializer),
									"xsInput" + i.ToString(),
									new CodeObjectCreateExpression(
										typeof(XmlSerializer),
										new CodeTypeOfExpression(typesWSInput[i]),
										new CodeVariableReferenceExpression("root" + i.ToString()))));
							codeIfXnNotNULL.TrueStatements.Add(	// obj = xsInput0.Deserialize(msInput);
								new CodeAssignStatement(
									new CodeVariableReferenceExpression("obj" + i.ToString()),
									new CodeMethodInvokeExpression(
										new CodeVariableReferenceExpression("xsInput" + i.ToString()),
										"Deserialize",
										new CodeVariableReferenceExpression("msInput" + i.ToString()))));
						}
						codeIfXnNotNULL.TrueStatements.Add(
							new CodeConditionStatement(
								new CodeBinaryOperatorExpression(
									new CodeBinaryOperatorExpression(
										new CodeVariableReferenceExpression("obj" + i.ToString()),
										CodeBinaryOperatorType.IdentityInequality,
										new CodePrimitiveExpression(null)),
									CodeBinaryOperatorType.BooleanAnd,
									new CodeBinaryOperatorExpression(
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("obj" + i.ToString()),
											"GetType"),
										CodeBinaryOperatorType.ValueEquality,
										new CodeTypeOfExpression(typesWSInput[i]))),
								new CodeStatement[] {
										new CodeAssignStatement(
											new CodeVariableReferenceExpression("inputWS" + i.ToString()),
											new CodeCastExpression(
												typesWSInput[i],
												new CodeVariableReferenceExpression("obj" + i.ToString()))),
									},
								new CodeStatement[] {
										typesWSInput[i].IsValueType ?
										new CodeAssignStatement(
											new CodeVariableReferenceExpression("inputWS" + i.ToString()),
											new CodeDefaultValueExpression(new CodeTypeReference(typesWSInput[i]))) :
										new CodeAssignStatement(
											new CodeVariableReferenceExpression("inputWS" + i.ToString()),
											new CodePrimitiveExpression(null))
									}));
						codeIfXnNotNULL.TrueStatements.Add(	// msInput.Close();
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("msInput" + i.ToString()),
								"Close"));
						methSvcCall.Statements.Add(codeIfXnNotNULL);
					}
					#endregion
				}
				#endregion

				#region Initialize Web Service Call
				Type typeClient = null;
				string fieldnameWSOutput = null;
				string fieldnameWaitOutput = null;
				if ( sendMsmq == null && receiveMsmq == null ) {
					fieldnameWSOutput = c_outputWS + ( wmCallback != null ? wmCallback.Name : webmeth.Name );
					fieldnameWaitOutput = c_wait + ( wmCallback != null ? wmCallback.Name : webmeth.Name );
					typeClient = GetClientTypeByContactTypeRef(codeContracts, typeRefLogActContract, typeProvider);
				}
				if ( hasOutput && typesWSOutput != null && typesWSOutput.Count > 0 ) {
					if ( currentSvcGenType == ServiceGenerationType.SystemWebService ) {
						#region initialize async system.web.service call
						// declare output field
						CodeMemberField fieldWSOutput = new CodeMemberField();
						fieldWSOutput.Attributes = MemberAttributes.Final | MemberAttributes.Private;
						fieldWSOutput.Name = fieldnameWSOutput;
						fieldWSOutput.Type = new CodeTypeReference(typesWSOutput[0]);
						ctdServices.Members.Add(fieldWSOutput);
						// _outputWSX = null;
						if ( typesWSOutput[0].IsValueType ) {
							methSvcCall.Statements.Add(
								new CodeAssignStatement(
									new CodeFieldReferenceExpression(null, fieldnameWSOutput),
									new CodeDefaultValueExpression(new CodeTypeReference(typesWSOutput[0]))));
						} else {
							methSvcCall.Statements.Add(
								new CodeAssignStatement(
									new CodeFieldReferenceExpression(null, fieldnameWSOutput),
									new CodePrimitiveExpression(null)));
						}
						// create AutoResetEvent member field
						CodeMemberField fieldWait = new CodeMemberField();
						fieldWait.Attributes = MemberAttributes.Final | MemberAttributes.Private;
						fieldWait.Name = fieldnameWaitOutput;
						fieldWait.Type = new CodeTypeReference(typeof(AutoResetEvent));
						ctdServices.Members.Add(fieldWait);
						// _waitX = new AutoResetEvent(false);
						methSvcCall.Statements.Add(
							new CodeAssignStatement(
								new CodeFieldReferenceExpression(null, fieldnameWaitOutput),
								new CodeObjectCreateExpression(
									typeof(AutoResetEvent), new CodePrimitiveExpression(false))));
						#endregion
					} else {
						if ( wmCallback != null ) {
							#region initialize callback wcf webservice call
							Debug.WriteLine("Callback Method: " + wmCallback.Name);
							// search for existing elements
							Type typeICallback = null;
							object[] custattribs = typeClient.GetCustomAttributes(typeof(ServiceContractAttribute), true);
							if ( custattribs != null && custattribs.Length > 0 ) {
								foreach ( object obj in custattribs ) {
									AttributeInfoAttribute aia = obj as AttributeInfoAttribute;
									if ( aia != null && aia.AttributeInfo.AttributeType == typeof(ServiceContractAttribute) ) {
										foreach ( object var in aia.AttributeInfo.ArgumentValues ) {
											if ( var is CodeTypeOfExpression ) {
												typeICallback = typeProvider.GetType(( (CodeTypeOfExpression)var ).Type.BaseType);
												break;
											}
										}
										if ( typeICallback != null ) break;
									}
								}
							}
							if ( typeICallback != null ) {
								ImplementCallbackInterface(ctdServices, typeICallback);
								// _outputWSX = null;
								for ( int i = 0; i < typesWSOutput.Count; i++ ) {
									if ( typesWSOutput[i].IsValueType ) {
										methSvcCall.Statements.Add(
											new CodeAssignStatement(
												new CodeFieldReferenceExpression(null, fieldnameWSOutput + i.ToString()),
												new CodeDefaultValueExpression(new CodeTypeReference(typesWSOutput[i]))));
									} else {
										methSvcCall.Statements.Add(
											new CodeAssignStatement(
												new CodeFieldReferenceExpression(null, fieldnameWSOutput + i.ToString()),
												new CodePrimitiveExpression(null)));
									}
								}
								// _waitX = new AutoResetEvent(false);
								methSvcCall.Statements.Add(
									new CodeAssignStatement(
										new CodeFieldReferenceExpression(null, fieldnameWaitOutput),
										new CodeObjectCreateExpression(
											typeof(AutoResetEvent), new CodePrimitiveExpression(false))));
							}
							#endregion
						} else if ( !generateAsyncInvoke ) {
							#region declare output variable
							fieldnameWSOutput = "outputWS";
							if ( typesWSOutput[0].IsValueType ) {
								methSvcCall.Statements.Add(
									new CodeVariableDeclarationStatement(
										typesWSOutput[0],
										fieldnameWSOutput,
										new CodeDefaultValueExpression(new CodeTypeReference(typesWSOutput[0]))));
							} else {
								methSvcCall.Statements.Add(
									new CodeVariableDeclarationStatement(
										typesWSOutput[0],
										fieldnameWSOutput,
										new CodePrimitiveExpression(null)));
							}
							#endregion
						}
					}
				}
				#endregion

				#region Do Web Service Call
				if ( typeClient == null && ( sendMsmq == null && receiveMsmq == null ) ) {
					MessageBox.Show("Type not available: " + websvc.Name + "Contract." + websvc.Name + "Client");
				} else {
					if ( currentSvcGenType == ServiceGenerationType.SystemWebService ) {
						#region System Web Service
						// use classic System.Web.Services style
						// ServiceClient client = new ServiceClient();
						methSvcCall.Statements.Add(
							new CodeVariableDeclarationStatement(
								typeClient,
								"client",
								new CodeObjectCreateExpression(
									typeClient)));
						// client.Url = "WEBSVC_URI";
						//methSvcCall.Statements.Add(
						//    new CodeAssignStatement(
						//        new CodePropertyReferenceExpression(
						//            new CodeVariableReferenceExpression("client"),
						//            "Url"),
						//        new CodePrimitiveExpression(websvc.Uri)));
						// START: tryClientCall
						CodeTryCatchFinallyStatement tryClientCall = new CodeTryCatchFinallyStatement();
						// client.Discover();
						tryClientCall.TryStatements.Add(
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("client"),
								"Discover"));
						if ( hasOutput ) {
							// add completed event handler method
							CodeMemberMethod methWSCompleted = new CodeMemberMethod();
							methWSCompleted.Attributes = MemberAttributes.Final | MemberAttributes.Private;
							methWSCompleted.Name = string.Format(cClientXCompleted, methContract.Name);
							methWSCompleted.Parameters.Add(
								new CodeParameterDeclarationExpression(
									typeof(object), "sender"));
							methWSCompleted.Parameters.Add(
								new CodeParameterDeclarationExpression(
									contractnspace + "." + methContract.Name + cCompletedEventArgs, "e"));
							methWSCompleted.Statements.Add(
								new CodeAssignStatement(
									new CodeFieldReferenceExpression(null, fieldnameWSOutput),
									new CodePropertyReferenceExpression(
										new CodeVariableReferenceExpression("e"), "Result")));
							methWSCompleted.Statements.Add(
								new CodeMethodInvokeExpression(
									new CodeFieldReferenceExpression(null, fieldnameWaitOutput),
									"Set"));
							ctdServices.Members.Add(methWSCompleted);
							// register event handler
							tryClientCall.TryStatements.Add(
								new CodeAttachEventStatement(
									new CodeVariableReferenceExpression("client"),
									methContract.Name + cCompleted,
									new CodeObjectCreateExpression(
										contractnspace + "." + methContract.Name + cCompletedEventHandler,
										new CodeMethodReferenceExpression(null,
											string.Format(cClientXCompleted, methContract.Name)))));
						}
						// [outputWS0 = ]client.Method([inputWS0]);
						if ( hasOutput && hasInput ) {
							// call async method
							CodeExpression[] parameters = new CodeExpression[typesWSInput.Count];
							for ( int i = 0; i < typesWSInput.Count; i++ ) {
								parameters[i] = new CodeVariableReferenceExpression("inputWS" + i.ToString());
							}
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("client"),
									methContract.Name + cAsync,
									parameters));
							// _waitX.WaitOne();
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeFieldReferenceExpression(null, fieldnameWaitOutput),
									"WaitOne"));
						} else if ( hasOutput ) {
							// call async method
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("client"),
									methContract.Name + cAsync));
							// _waitX.WaitOne();
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeFieldReferenceExpression(null, fieldnameWaitOutput),
									"WaitOne"));
						} else if ( hasInput ) {
							CodeExpression[] parameters = new CodeExpression[typesWSInput.Count];
							for ( int i = 0; i < typesWSInput.Count; i++ ) {
								parameters[i] = new CodeVariableReferenceExpression("inputWS" + i.ToString());
							}
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("client"),
									methContract.Name,
									parameters));
						} else {
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("client"),
									methContract.Name));
						}
						// CATCH: tryClientCall
						CreateCatchClause(tryClientCall, "timeProblem", "The service operation timed out. ",
							typeof(TimeoutException));
						CreateCatchClause(tryClientCall, "ex", "Generic Exception. ", typeof(Exception));
						// END: tryClientCall 
						methSvcCall.Statements.Add(tryClientCall);
						#endregion
					} else if ( currentSvcGenType == ServiceGenerationType.HumanActivityService ) {
						#region Human Activity Service
						const string participants = "listParticipants";
						const string partString = "partString";
						methSvcCall.Statements.Add(
							new CodeCommentStatement("declare and init included / excluded participants strings"));
						//List<ParticipantItems> participants = null;
						CodeTypeReference typeRefListOfPartItems = new CodeTypeReference(typeof(List<>));
						typeRefListOfPartItems.TypeArguments.Add(typeof(ParticipantItem));
						methSvcCall.Statements.Add(
							new CodeVariableDeclarationStatement(
								typeRefListOfPartItems,
								participants,
								new CodeObjectCreateExpression(typeRefListOfPartItems)));
						//foreach component participant:
						//ai.AddParticipant(participantType, participantId, participationType);
						foreach ( var part in logact.ExtendedProperties.HumanComponentProperties.Participants ) {
							methSvcCall.Statements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression(participants),
									"Add",
									new CodeObjectCreateExpression(
										typeof(ParticipantItem),
										new CodePropertyReferenceExpression(
											new CodeTypeReferenceExpression(typeof(ParticipantType)),
											part.Type.ToString()),
										new CodePrimitiveExpression(part.ID),
										new CodePropertyReferenceExpression(
											new CodeTypeReferenceExpression(typeof(ParticipationType)),
											part.ParticipationType.ToString()))));
						}
						if ( logact != null ) {
							bool isPartStringCreated = false;
							addSplitMethod(ctdServices);
							foreach ( HumanComponentParticipant part in logact.ExtendedProperties.HumanComponentProperties.Participants ) {
								if ( part.ParticipationType == ParticipationType.IncludedParticipant &&
									 part.Type == ParticipantType.ParticipantRule ) {
									RepositoryBusinessRule partrule = repSvc.GetItem<RepositoryBusinessRule>(part.ID);
									if ( partrule == null || partrule.IsDeleted ) {
										continue; // NEXT HumanComponentParticipant
									}
									if ( !isPartStringCreated ) {
										//string partString;
										methSvcCall.Statements.Add(
											new CodeVariableDeclarationStatement(
												typeof(string),
												partString));
										isPartStringCreated = true;
									}
									methSvcCall.Statements.Add(
										new CodeCommentStatement("evaluate include participant rule '" + partrule.Name + "'"));
									//partString = Rules.PartRule1(_orchestration.TravelRequestTotalPrice);
									CodeMethodInvokeExpression invokeRuleExpr =
										GetBusinessRuleInvokeExpression(
											codeRules,
											new CodeFieldReferenceExpression(
												new CodeThisReferenceExpression(),
												"_orchestration"),
											partrule, namespaceRules);
									if ( invokeRuleExpr != null ) {
										methSvcCall.Statements.Add(
											new CodeAssignStatement(
												new CodeVariableReferenceExpression(partString),
												invokeRuleExpr));
										//splitParticipants(partString, ParticipationType.IncludedParticipant, ref listParticipants);
										methSvcCall.Statements.Add(
											new CodeMethodInvokeExpression(
												new CodeThisReferenceExpression(),
												"splitParticipants",
												new CodeVariableReferenceExpression(partString),
												new CodePropertyReferenceExpression(
													new CodeTypeReferenceExpression(typeof(ParticipationType)),
													"IncludedParticipant"),
												new CodeDirectionExpression(
													FieldDirection.Ref,
													new CodeVariableReferenceExpression(participants))));
										//methSvcCall.Statements.Add(
										//    CreateCheckAndAppendPartStringStatement(includedParticipants, partString));
									}
								} else if ( part.ParticipationType == ParticipationType.ExcludedParticipant &&
											part.Type == ParticipantType.ParticipantRule ) {
									RepositoryBusinessRule partrule = repSvc.GetItem<RepositoryBusinessRule>(part.ID);
									if ( partrule == null || partrule.IsDeleted ) {
										continue; // NEXT HumanComponentParticipant
									}
									methSvcCall.Statements.Add(
										new CodeCommentStatement("evaluate exclude participant rule '" + partrule.Name + "'"));
									//partString = Rules.PartRule1(_orchestration.TravelRequestTotalPrice);
									CodeMethodInvokeExpression invokeRuleExpr =
										GetBusinessRuleInvokeExpression(
											codeRules,
											new CodeFieldReferenceExpression(
												new CodeThisReferenceExpression(),
												"_orchestration"),
											partrule, namespaceRules);
									if ( invokeRuleExpr != null ) {
										methSvcCall.Statements.Add(
											new CodeAssignStatement(
												new CodeVariableReferenceExpression(partString),
												invokeRuleExpr));
										//methSvcCall.Statements.Add(
										//    CreateCheckAndAppendPartStringStatement(excludedParticipants, partString));
									} // if ( invokeRuleExpr != null )
								}
							} // foreach ( HumanComponentParticipant part in logact...Participants )
						} // if ( logact != null )
						// ServiceClient client = new ServiceClient();
						methSvcCall.Statements.Add(
							new CodeVariableDeclarationStatement(
								typeClient,
								"client",
								new CodeObjectCreateExpression(
									typeClient)));
						CodeTryCatchFinallyStatement tryClientCall = new CodeTryCatchFinallyStatement();
						// [outputWS0 = ]client.DoHumanActivity(workflowInstanceId, 
						//		activityName, processName, subject, targetURLKey, input, participants);
						if ( hasOutput && hasInput ) {
							tryClientCall.TryStatements.Add(
								new CodeAssignStatement(
									new CodeVariableReferenceExpression("outputWS"),
									new CodeMethodInvokeExpression(
										new CodeVariableReferenceExpression("client"),
										"DoHumanActivity",
										new CodePropertyReferenceExpression(
											new CodeFieldReferenceExpression(
												new CodeThisReferenceExpression(), "_orchestration"),
											"InstanceId"),
										new CodePrimitiveExpression(logact.ExtendedProperties.HumanComponentProperties.ActivityName),
										new CodePrimitiveExpression(logact.ExtendedProperties.HumanComponentProperties.ProcessName),
										new CodePrimitiveExpression(logact.ExtendedProperties.HumanComponentProperties.Subject),
										new CodePrimitiveExpression(endpointConfigName/*websvc.Uri*/),
										new CodeVariableReferenceExpression("inputWS0"),
										new CodeVariableReferenceExpression(participants))));
						} else if ( hasOutput ) {
							tryClientCall.TryStatements.Add(
								new CodeAssignStatement(
									new CodeVariableReferenceExpression("outputWS"),
									new CodeMethodInvokeExpression(
										new CodeVariableReferenceExpression("client"),
										"DoHumanActivity",
										new CodePropertyReferenceExpression(
											new CodeFieldReferenceExpression(
												new CodeThisReferenceExpression(), "_orchestration"),
											"InstanceId"),
										new CodePrimitiveExpression(logact.ExtendedProperties.HumanComponentProperties.ActivityName),
										new CodePrimitiveExpression(logact.ExtendedProperties.HumanComponentProperties.ProcessName),
										new CodePrimitiveExpression(logact.ExtendedProperties.HumanComponentProperties.Subject),
										new CodePrimitiveExpression(endpointConfigName/*websvc.Uri*/),
										new CodePrimitiveExpression(null),
										new CodeVariableReferenceExpression(participants))));
						} else {
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("client"),
									"DoHumanActivity",
									new CodePropertyReferenceExpression(
										new CodeFieldReferenceExpression(
											new CodeThisReferenceExpression(), "_orchestration"),
										"InstanceId"),
									new CodePrimitiveExpression(logact.ExtendedProperties.HumanComponentProperties.ActivityName),
									new CodePrimitiveExpression(logact.ExtendedProperties.HumanComponentProperties.ProcessName),
									new CodePrimitiveExpression(logact.ExtendedProperties.HumanComponentProperties.Subject),
									new CodePrimitiveExpression(endpointConfigName/*websvc.Uri*/),
									new CodeVariableReferenceExpression("inputWS0"),
									new CodeVariableReferenceExpression(participants)));
						}
						// CATCH: tryClientCall
						CreateCatchClause(tryClientCall, "timeProblem", "The service operation timed out. ",
							typeof(TimeoutException));
						CreateCatchClause(tryClientCall, "ex", "Generic Exception. ", typeof(Exception));
						// END: tryClientCall 
						methSvcCall.Statements.Add(tryClientCall);
						#endregion
					} else if ( currentSvcGenType == ServiceGenerationType.MessageQueueService ) {
						#region Message Queue
						CodeTryCatchFinallyStatement tryCommunication = new CodeTryCatchFinallyStatement();
						if ( sendMsmq != null ) {
							tryCommunication.TryStatements.Add(
								new CodeVariableDeclarationStatement(
									typeof(MessageQueue),
									cSendQueueName,
									new CodeObjectCreateExpression(
										typeof(MessageQueue),
										new CodePrimitiveExpression(sendMsmq.Path))));
							tryCommunication.TryStatements.Add(
								new CodeAssignStatement(
									new CodePropertyReferenceExpression(
										new CodeVariableReferenceExpression(
											cSendQueueName),
										"Formatter"),
									new CodeObjectCreateExpression(
										typeof(XmlMessageFormatter),
										new CodeArrayCreateExpression(
											typeof(Type[]),
											new CodeExpression[]{
										new CodeTypeOfExpression(typeof(XmlDocument))
									}))));
						}
						if ( receiveMsmq != null && !generateAsyncInvoke ) {
							tryCommunication.TryStatements.Add(
								new CodeVariableDeclarationStatement(
									typeof(MessageQueue),
									cReceiveQueueName,
									new CodeObjectCreateExpression(
										typeof(MessageQueue),
										new CodePrimitiveExpression(receiveMsmq.Path))));
							tryCommunication.TryStatements.Add(
								new CodeAssignStatement(
									new CodePropertyReferenceExpression(
										new CodeVariableReferenceExpression(
											cReceiveQueueName),
										"Formatter"),
									new CodeObjectCreateExpression(
										typeof(XmlMessageFormatter),
										new CodeArrayCreateExpression(
											typeof(Type[]),
											new CodeExpression[]{
										new CodeTypeOfExpression(typeof(XmlDocument))
									}))));
						}
						CompositeActivity root = logact.Workflow.GetRootActivity() as CompositeActivity;
						bool isSync = ( !generateAsyncInvoke && sendMsmq != null && receiveMsmq != null );
						LogicalAsyncEndActivity endAct = null;
						foreach ( Activity act in root.GetNestedActivities() ) {
							endAct = act as LogicalAsyncEndActivity;
							if ( endAct == null ) continue;
							if ( endAct.StartActivityName == logcap.Name ) break;
						}
						if ( sendMsmq != null ) {
							LogicalAsyncStartActivity msmqAct = root.GetActivityByLogicalActivityID<LogicalAsyncStartActivity>(logact.ID);
							tryCommunication.TryStatements.Add(
								new CodeVariableDeclarationStatement(
									typeof(System.Messaging.Message),
									"request",
									new CodeObjectCreateExpression(
										typeof(System.Messaging.Message),
										new CodeVariableReferenceExpression(
											"input"))));
							tryCommunication.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression(
										cSendQueueName),
									"Send",
									new CodeVariableReferenceExpression(
										"request")));
							// save generated id for later use (@receive)
							if ( msmqAct != null ) {
								tryCommunication.TryStatements.Add(
									new CodeAssignStatement(
										new CodeFieldReferenceExpression(
											new CodeTypeReferenceExpression(ctdServices.Name),
											string.Format("{0}CorrelationId", msmqAct.Name)),
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression("request"),
											"Id")));
							}
							#region AsyncMSMQ
							if ( generateAsyncInvoke ) {
								//LogicalAsyncState state = new LogicalAsyncState(
								//    context.GetService<WorkflowQueuingService>(),
								//    "METHOD" + _orchestration.InstanceId.ToString(),
								//    _orchestration.InstanceId);
								tryCommunication.TryStatements.Add(
									new CodeVariableDeclarationStatement(
										typeof(LogicalAsyncState),
										"state",
										new CodeObjectCreateExpression(
											typeof(LogicalAsyncState),
											new CodeMethodInvokeExpression(
												new CodeMethodReferenceExpression(
													new CodeArgumentReferenceExpression("context"),
													"GetService",
													new CodeTypeReference(typeof(WorkflowQueuingService)))),
											new CodeBinaryOperatorExpression(
												new CodePrimitiveExpression(logcap.Name),
												CodeBinaryOperatorType.Add,
												new CodeMethodInvokeExpression(
													new CodePropertyReferenceExpression(
														new CodeFieldReferenceExpression(
															new CodeThisReferenceExpression(),
															"_orchestration"),
														"InstanceId"),
													"ToString")),
											new CodePropertyReferenceExpression(
												new CodeFieldReferenceExpression(
													new CodeThisReferenceExpression(),
													"_orchestration"),
												"InstanceId"))));
								//AsyncService asyncSvc = context.GetService<AsyncService>();
								tryCommunication.TryStatements.Add(
									new CodeVariableDeclarationStatement(
										typeof(AsyncService),
										"asyncSvc",
										new CodeMethodInvokeExpression(
											new CodeMethodReferenceExpression(
												new CodeArgumentReferenceExpression("context"),
												"GetService",
												new CodeTypeReference(typeof(AsyncService))))));
								//asyncSvc.RegisterAsyncWebServiceCall(state, null)
								//if ( isSync ) {
								tryCommunication.TryStatements.Add(
									new CodeMethodInvokeExpression(
										new CodeVariableReferenceExpression("asyncSvc"),
										"RegisterAsyncWebServiceCall",
										new CodeVariableReferenceExpression("state"),
										new CodePrimitiveExpression(null)));
								//} else if ( receiveMsmq != null && endAct != null ) {
								//    tryCommunication.TryStatements.Add(
								//        new CodeMethodInvokeExpression(
								//            new CodeVariableReferenceExpression("asyncSvc"),
								//            "RegisterAsyncWebServiceCall",
								//            new CodeVariableReferenceExpression("state"),
								//            new CodeMethodReferenceExpression(
								//                new CodeThisReferenceExpression(),
								//                string.Format("{0}CompletedCallback", endAct.Name))));
								//}
								// init workflow queue
								//initWorkflowQueue(state.WorkflowQueuingService, state.WorkflowQueueName);
								//CreateInitWorkflowQueueMethod(ctdServices);
								//tryCommunication.TryStatements.Add(
								//    new CodeMethodInvokeExpression(
								//        new CodeThisReferenceExpression(),
								//        _cInitWorkflowQueueMethodName,
								//        new CodePropertyReferenceExpression(
								//            new CodeVariableReferenceExpression("state"),
								//            "WorkflowQueuingService"),
								//        new CodePropertyReferenceExpression(
								//            new CodeVariableReferenceExpression("state"),
								//            "WorkflowQueueName")));
								//// state.WorkflowInstance.EnqueueItem(state.WorkflowQueueName, state, null, null);
								//tryCommunication.TryStatements.Add(
								//    new CodeMethodInvokeExpression(
								//        new CodePropertyReferenceExpression(
								//            new CodeVariableReferenceExpression("state"),
								//            "WorkflowInstance"),
								//        "EnqueueItem",
								//        new CodePropertyReferenceExpression(
								//            new CodeVariableReferenceExpression("state"),
								//            "WorkflowQueueName"),
								//        new CodeVariableReferenceExpression("state"),
								//        new CodePrimitiveExpression(null),
								//        new CodePrimitiveExpression(null)));
								////state.Client = client;
								//tryCommunication.TryStatements.Add(
								//    new CodeAssignStatement(
								//        new CodePropertyReferenceExpression(
								//            new CodeVariableReferenceExpression("state"),
								//            "Client"),
								//        new CodeVariableReferenceExpression(cSendQueueName)));

							}
							#endregion
						}
						if ( receiveMsmq != null ) {
							LogicalAsyncEndActivity msmqAct = root.GetActivityByLogicalActivityID<LogicalAsyncEndActivity>(logact.ID);
							if ( isSync || ( msmqAct != null && msmqAct.StartActivityName != null ) ) {
								tryCommunication.TryStatements.Add(
									new CodeAssignStatement(
										new CodePropertyReferenceExpression(
											new CodePropertyReferenceExpression(
												new CodeVariableReferenceExpression(
													cReceiveQueueName),
												"MessageReadPropertyFilter"),
											"CorrelationId"),
										new CodePrimitiveExpression(true)));
								if ( isSync ) {
									tryCommunication.TryStatements.Add(
										new CodeVariableDeclarationStatement(
											typeof(System.Messaging.Message),
											"response",
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression(cReceiveQueueName),
												"ReceiveByCorrelationId",
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("request"),
													"Id"),
												new CodeFieldReferenceExpression(
													new CodeTypeReferenceExpression(
														typeof(MessageQueue)),
													"InfiniteTimeout"))));
								} else {
									tryCommunication.TryStatements.Add(
										new CodeVariableDeclarationStatement(
											typeof(System.Messaging.Message),
											"response",
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression(cReceiveQueueName),
												"ReceiveByCorrelationId",
												new CodeFieldReferenceExpression(
													new CodeTypeReferenceExpression(ctdServices.Name),
													string.Format("{0}CorrelationId", msmqAct.StartActivityName)),
												new CodeFieldReferenceExpression(
													new CodeTypeReferenceExpression(
														typeof(MessageQueue)),
													"InfiniteTimeout"))));
								}
								tryCommunication.TryStatements.Add(
									new CodeAssignStatement(
										new CodeVariableReferenceExpression(
											"outputWS"),
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression(
												"response"),
											"Body")));
							} else {
								if ( endAct != null ) {
									CodeMemberMethod methCompleted = new CodeMemberMethod();
									methCompleted.Attributes = MemberAttributes.Public | MemberAttributes.Final;
									methCompleted.Name = string.Format("{0}Completed", endAct.StartActivityName);
									/*methCompleted.Parameters.Add(
										new CodeParameterDeclarationExpression(
											typeof(LogicalAsyncState),
											"state"));*/
									methCompleted.Statements.Add(
										new CodeVariableDeclarationStatement(
											typeof(MessageQueue),
											"client",
											new CodeObjectCreateExpression(
												typeof(MessageQueue),
												new CodePrimitiveExpression(
													receiveMsmq.Path))
										/*new CodeCastExpression(
											typeof(MessageQueue),
											new CodePropertyReferenceExpression(
												new CodeArgumentReferenceExpression("state"),
												"Client"))*/
																));
									methCompleted.ReturnType = new CodeTypeReference(string.Format("{0}.{1}", namespaceData, logact.OutputBusinessObject.Name));
									methCompleted.Statements.Add(
										new CodeVariableDeclarationStatement(
											typeof(MessageQueue),
											cReceiveQueueName,
											new CodeObjectCreateExpression(
												typeof(MessageQueue),
												new CodePrimitiveExpression(receiveMsmq.Path))));
									methCompleted.Statements.Add(
										new CodeAssignStatement(
											new CodePropertyReferenceExpression(
												new CodeVariableReferenceExpression(
													cReceiveQueueName),
												"Formatter"),
											new CodeObjectCreateExpression(
												typeof(XmlMessageFormatter),
												new CodeArrayCreateExpression(
													typeof(Type[]),
													new CodeExpression[]{
										new CodeTypeOfExpression(typeof(XmlDocument))
									}))));
									methCompleted.Statements.Add(
										new CodeAssignStatement(
											new CodePropertyReferenceExpression(
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression(
														cReceiveQueueName),
													"MessageReadPropertyFilter"),
												"CorrelationId"),
											new CodePrimitiveExpression(true)));
									methCompleted.Statements.Add(
										new CodeVariableDeclarationStatement(
											typeof(System.Messaging.Message),
											"response",
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression(cReceiveQueueName),
												"ReceiveByCorrelationId",
												new CodeFieldReferenceExpression(
													new CodeTypeReferenceExpression(ctdServices.Name),
													string.Format("{0}CorrelationId", endAct.StartActivityName)),
												new CodeFieldReferenceExpression(
													new CodeTypeReferenceExpression(
														typeof(MessageQueue)),
													"InfiniteTimeout"))));
									methCompleted.Statements.Add(
										new CodeMethodReturnStatement(
											new CodeMethodInvokeExpression(
												mapoutTargetObj,
												methOutMap.Name,
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression(
														"response"),
													"Body"))));
									//methCompleted.Statements.Add(
									//    new CodeMethodReturnStatement(
									//        new CodeCastExpression(
									//            string.Format("{0}.{1}", namespaceData, logact.OutputBusinessObject.Name),
									//            new CodePropertyReferenceExpression(
									//                new CodeVariableReferenceExpression("response"),
									//                "Body"))));
									ctdServices.Members.Add(methCompleted);
								}
							}
						}
						//tryCommunication.TryStatements.Add(
						//    new CodeVariableDeclarationStatement(
						//        typeof(System.Messaging.Message),
						//        "message",
						//        new CodeMethodInvokeExpression(
						//            new CodeVariableReferenceExpression("queue"),
						//            "Receive")));

						//tryCommunication.TryStatements.Add(
						//    new CodeAssignStatement(
						//        new CodeVariableReferenceExpression(
						//            "outputWS"),
						//        new CodePropertyReferenceExpression(
						//            new CodeMethodInvokeExpression(
						//                new CodeVariableReferenceExpression("queue"),
						//                "Receive"),
						//            "Body")));
						//MessageQueue queue = null; queue.Receive();
						CreateCatchClause(tryCommunication, "timeProblem", "The service operation timed out. ",
							typeof(TimeoutException), false);
						CreateCatchClause(tryCommunication, "unknownFault", "An unknown exception was received. ",
							typeof(FaultException), false);
						CreateCatchClause(tryCommunication, "commProblem", "There was a communication problem. ",
							typeof(CommunicationException), false);
						CreateCatchClause(tryCommunication, "ex", "Generic Exception. ",
							typeof(Exception), false);

						methSvcCall.Statements.Add(tryCommunication);
						#endregion
					} else {
						#region WCF Service
						if ( string.IsNullOrEmpty(websvc.ClientFullName) ) {
							typeClient = typeProvider.GetType(websvc.Name + "Contract." + websvc.Name + "Client");
						} else {
							typeClient = typeProvider.GetType(websvc.ClientFullName);
						}
						Type typeInterface = null;
						if ( !string.IsNullOrEmpty(websvc.InterfaceFullName) ) {
							typeInterface = typeProvider.GetType(websvc.InterfaceFullName);
						}
						if ( string.IsNullOrEmpty(endpointConfigName) ) {
							#region no endpoint configuration available in the config
							// use wcf to call webservice
							methSvcCall.Statements.Add(
								new CodeVariableDeclarationStatement(
									typeof(Uri),
									"uriService",
									new CodeObjectCreateExpression(
										typeof(Uri),
										new CodePrimitiveExpression(websvc.Uri))));
							// create wcf client and call webmethod
							if ( websvc.Uri.ToLower().EndsWith(".asmx") ) {
								methSvcCall.Statements.Add(
									new CodeVariableDeclarationStatement(
										typeof(BasicHttpBinding),
										"bind",
										new CodeObjectCreateExpression(typeof(BasicHttpBinding))));
							} else {
								if ( bindings == null || bindings.Count == 0 ) {
									methSvcCall.Statements.Add(
										new CodeVariableDeclarationStatement(
											typeof(WSHttpBinding),
											"bind",
											new CodeObjectCreateExpression(typeof(WSHttpBinding))));
								} else {
									System.ServiceModel.Channels.Binding bind = null;
									foreach ( System.ServiceModel.Channels.Binding currentbind in bindings ) {
										bind = currentbind;
										if ( !( currentbind is System.ServiceModel.Channels.CustomBinding ) ) {
											break;
										}
									}
									if ( bind == null || bind is System.ServiceModel.Channels.CustomBinding ) {
										if ( bind == null ) {
											bind = new WSHttpBinding();
										} else if ( bind.Name.ToLower().StartsWith("basichttpbinding") ) {
											bind = new BasicHttpBinding();
										} else if ( bind.Name.ToLower().StartsWith("wshttpbinding") ) {
											bind = new WSHttpBinding();
										} else if ( bind.Name.ToLower().StartsWith("wsdualhttpbinding") ) {
											bind = new WSDualHttpBinding();
										} else if ( bind.Name.ToLower().StartsWith("nettcpbinding") ) {
											bind = new NetTcpBinding();
										}
									}
									methSvcCall.Statements.Add(
										new CodeVariableDeclarationStatement(
											typeof(System.ServiceModel.Channels.Binding),
											"bind",
											new CodeObjectCreateExpression(bind.GetType())));
								}
							}
							methSvcCall.Statements.Add(
								new CodeVariableDeclarationStatement(
									typeof(EndpointAddress),
									"epService",
									new CodeObjectCreateExpression(
										typeof(EndpointAddress),
										new CodeVariableReferenceExpression("uriService"))));
							if ( wmCallback != null ) {
								methSvcCall.Statements.Add(
									new CodeVariableDeclarationStatement(
										typeClient,
										"client",
										new CodeObjectCreateExpression(
											typeClient,
											new CodeObjectCreateExpression(
												typeof(InstanceContext),
												new CodeThisReferenceExpression()),
											new CodeVariableReferenceExpression("bind"),
											new CodeVariableReferenceExpression("epService"))));
							} else {
								methSvcCall.Statements.Add(
									new CodeVariableDeclarationStatement(
										typeClient,
										"client",
										new CodeObjectCreateExpression(
											typeClient,
											new CodeVariableReferenceExpression("bind"),
											new CodeVariableReferenceExpression("epService"))));
							}
							#endregion
						} else {
							#region endpoint configuration available in the config file
							if ( wmCallback != null ) {
								methSvcCall.Statements.Add(
									new CodeVariableDeclarationStatement(
										typeClient,
										"client",
										new CodeObjectCreateExpression(
											typeClient,
											new CodeObjectCreateExpression(
												typeof(InstanceContext),
												new CodeThisReferenceExpression()),
											new CodePrimitiveExpression(endpointConfigName))));
							} else {
								methSvcCall.Statements.Add(
									new CodeVariableDeclarationStatement(
										typeClient,
										"client",
										new CodeObjectCreateExpression(
											typeClient,
											new CodePrimitiveExpression(endpointConfigName))));
							}
							#endregion
						}
						CodeTryCatchFinallyStatement tryClientCall = new CodeTryCatchFinallyStatement();
						if ( isWSDualHttpBinding /*wmCallback != null*/ ) {
							#region Initialize Callback Endpoint
							//	if ( Environment.OSVersion.Version.Major < 6 ) {
							//		if ( client.Endpoint.Binding.GetType() == typeof(WSDualHttpBinding) ) {
							//			( (WSDualHttpBinding)client.Endpoint.Binding ).ClientBaseAddress =
							//				new Uri(string.Format("http://{0}:{1}/CallbackMethodName",
							//				System.Net.Dns.GetHostName(), findFreePort()));
							//		} else {
							//			...
							//		}
							//	}
							const string findFreePort = "findFreePort";
							bool freePortMethExists = false;
							foreach ( CodeTypeMember member in ctdServices.Members ) {
								if ( member.Name == findFreePort ) {
									freePortMethExists = true;
									break;
								}
							}
							if ( !freePortMethExists ) CreateFindFreePortMethod(findFreePort, ctdServices);
							CodeConditionStatement codeIfNotVista = new CodeConditionStatement();
							codeIfNotVista.Condition = new CodeBinaryOperatorExpression(
								new CodePropertyReferenceExpression(
									new CodePropertyReferenceExpression(
										new CodePropertyReferenceExpression(
											new CodeTypeReferenceExpression(typeof(Environment)),
											"OSVersion"),
										"Version"),
									"Major"),
								CodeBinaryOperatorType.LessThan,
								new CodePrimitiveExpression(6));
							CodeConditionStatement codeIfBindingIsWSDual = new CodeConditionStatement();
							codeIfBindingIsWSDual.Condition = new CodeBinaryOperatorExpression(
								new CodeMethodInvokeExpression(
									new CodePropertyReferenceExpression(
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression("client"),
											"Endpoint"),
										"Binding"),
									"GetType"),
								CodeBinaryOperatorType.ValueEquality,
								new CodeTypeOfExpression(typeof(WSDualHttpBinding)));
							codeIfBindingIsWSDual.TrueStatements.Add(
								new CodeAssignStatement(
									new CodePropertyReferenceExpression(
										new CodeCastExpression(
											typeof(WSDualHttpBinding),
											new CodePropertyReferenceExpression(
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("client"),
													"Endpoint"),
												"Binding")),
										"ClientBaseAddress"),
									new CodeObjectCreateExpression(
										typeof(Uri),
										new CodeMethodInvokeExpression(
											new CodeTypeReferenceExpression(typeof(string)),
											"Format",
											new CodePrimitiveExpression("http://{0}:{1}/{2}/Callback"),
											new CodeMethodInvokeExpression(
												new CodeTypeReferenceExpression(typeof(Dns)),
												"GetHostName"),
											new CodeMethodInvokeExpression(
												new CodeThisReferenceExpression(), findFreePort),
											new CodePrimitiveExpression(wmCallback != null ? wmCallback.Name : webmeth.Name)))));
							codeIfBindingIsWSDual.FalseStatements.Add(
								// if ( client.Endpoint.Binding.GetType() == typeof(CustomBinding) ) {
								new CodeConditionStatement(
									new CodeBinaryOperatorExpression(
										new CodeMethodInvokeExpression(
											new CodePropertyReferenceExpression(
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("client"),
													"Endpoint"),
												"Binding"),
											"GetType"),
										CodeBinaryOperatorType.ValueEquality,
										new CodeTypeOfExpression(typeof(CustomBinding))),
								// CustomBinding cb = (CustomBinding)client.Endpoint.Binding;
									new CodeVariableDeclarationStatement(
										typeof(CustomBinding), "cb",
										new CodeCastExpression(
											typeof(CustomBinding),
											new CodePropertyReferenceExpression(
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("client"),
													"Endpoint"),
												"Binding"))),
								// CompositeDuplexBindingElement cdbe =
								//	cb.Elements.Find<CompositeDuplexBindingElement>();
									new CodeVariableDeclarationStatement(
										typeof(CompositeDuplexBindingElement), "cdbe",
										new CodeMethodInvokeExpression(
											new CodeMethodReferenceExpression(
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("cb"),
													"Elements"),
												"Find",
												new CodeTypeReference(typeof(CompositeDuplexBindingElement))))),
								// if ( cdbe != null && cdbe.ClientBaseAddress == null ) {
									new CodeConditionStatement(
										new CodeBinaryOperatorExpression(
											new CodeBinaryOperatorExpression(
												new CodeVariableReferenceExpression("cdbe"),
												CodeBinaryOperatorType.IdentityInequality,
												new CodePrimitiveExpression(null)),
											CodeBinaryOperatorType.BooleanAnd,
											new CodeBinaryOperatorExpression(
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("cdbe"),
													"ClientBaseAddress"),
												CodeBinaryOperatorType.IdentityEquality,
												new CodePrimitiveExpression(null))),
								// cdbe.ClientBaseAddress =
								//	new Uri(string.Format("http://{0}:{1}/{2}",
								//			System.Net.Dns.GetHostName(), findFreePort(), "CallbackMethodName"))
										new CodeAssignStatement(
											new CodePropertyReferenceExpression(
												new CodeVariableReferenceExpression("cdbe"),
												"ClientBaseAddress"),
											new CodeObjectCreateExpression(
												typeof(Uri),
												new CodeMethodInvokeExpression(
													new CodeTypeReferenceExpression(typeof(string)),
													"Format",
													new CodePrimitiveExpression("http://{0}:{1}/{2}/Callback"),
													new CodeMethodInvokeExpression(
														new CodeTypeReferenceExpression(typeof(Dns)),
														"GetHostName"),
													new CodeMethodInvokeExpression(
														new CodeThisReferenceExpression(), findFreePort),
													new CodePrimitiveExpression(wmCallback != null ? wmCallback.Name : webmeth.Name)))))));

							codeIfNotVista.TrueStatements.Add(codeIfBindingIsWSDual);
							tryClientCall.TryStatements.Add(new CodeCommentStatement("workaround for non vista systems."));
							tryClientCall.TryStatements.Add(codeIfNotVista);
							#endregion
						}
						if ( generateAsyncInvoke && hasOutput ) {
							//LogicalAsyncState state = new LogicalAsyncState(
							//    context.GetService<WorkflowQueuingService>(),
							//    "METHOD" + _orchestration.InstanceId.ToString(),
							//    _orchestration.InstanceId);
							tryClientCall.TryStatements.Add(
								new CodeVariableDeclarationStatement(
									typeof(LogicalAsyncState),
									"state",
									new CodeObjectCreateExpression(
										typeof(LogicalAsyncState),
										new CodeMethodInvokeExpression(
											new CodeMethodReferenceExpression(
												new CodeArgumentReferenceExpression("context"),
												"GetService",
												new CodeTypeReference(typeof(WorkflowQueuingService)))),
										new CodeBinaryOperatorExpression(
											new CodePrimitiveExpression(logcap.Name),
											CodeBinaryOperatorType.Add,
											new CodeMethodInvokeExpression(
												new CodePropertyReferenceExpression(
													new CodeFieldReferenceExpression(
														new CodeThisReferenceExpression(),
														"_orchestration"),
													"InstanceId"),
												"ToString")),
										new CodePropertyReferenceExpression(
											new CodeFieldReferenceExpression(
												new CodeThisReferenceExpression(),
												"_orchestration"),
											"InstanceId"))));
							// init workflow queue
							//initWorkflowQueue(state.WorkflowQueuingService, state.WorkflowQueueName);
							CreateInitWorkflowQueueMethod(ctdServices);
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeThisReferenceExpression(),
									_cInitWorkflowQueueMethodName,
									new CodePropertyReferenceExpression(
										new CodeVariableReferenceExpression("state"),
										"WorkflowQueuingService"),
									new CodePropertyReferenceExpression(
										new CodeVariableReferenceExpression("state"),
										"WorkflowQueueName")));
							//AsyncService asyncSvc = context.GetService<AsyncService>();
							tryClientCall.TryStatements.Add(
								new CodeVariableDeclarationStatement(
									typeof(AsyncService),
									"asyncSvc",
									new CodeMethodInvokeExpression(
										new CodeMethodReferenceExpression(
											new CodeArgumentReferenceExpression("context"),
											"GetService",
											new CodeTypeReference(typeof(AsyncService))))));
							//state.Client = client;
							tryClientCall.TryStatements.Add(
								new CodeAssignStatement(
									new CodePropertyReferenceExpression(
										new CodeVariableReferenceExpression("state"),
										"Client"),
									new CodeVariableReferenceExpression("client")));
						}
						tryClientCall.TryStatements.Add(
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("client"),
								"Open"));
						CodeMemberMethod codeMethClient = getMethodFromCode(codeContracts, typeClient.FullName, webmeth);
						CodeExpression clientObject = new CodeVariableReferenceExpression("client");
						//if ( typeInterface != null && codeMethClient.PrivateImplementationType != null ) {
						//    clientObject = new CodeCastExpression(typeInterface,
						//        new CodeVariableReferenceExpression("client"));
						//}
						if ( generateAsyncInvoke && hasOutput ) {
							//asyncSvc.RegisterAsyncWebServiceCall(state, this.AsyncCompletedCallback)
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("asyncSvc"),
									"RegisterAsyncWebServiceCall",
									new CodeVariableReferenceExpression("state"),
									new CodePrimitiveExpression(null)
								/*new CodeMethodReferenceExpression(
										new CodeThisReferenceExpression(),
										string.Format("{0}CompletedCallback", methContract.Name))*/
																									   ));
							List<CodeExpression> parameters = new List<CodeExpression>();
							if ( hasInput ) {
								for ( int i = 0; i < typesWSInput.Count; i++ ) {
									parameters.Add(new CodeVariableReferenceExpression("inputWS" + i.ToString()));
								}
							}
							//parameters.Add(new CodePrimitiveExpression(null));
							parameters.Add(new CodeVariableReferenceExpression("state"));
							//tryClientCall.TryStatements.Add(
							//    new CodeAssignStatement(
							//        new CodePropertyReferenceExpression(
							//            new CodeVariableReferenceExpression("state"),
							//            "AsyncResult"),
							//        new CodeMethodInvokeExpression(
							//            clientObject,
							//            "Begin" + methContract.Name,
							//            parameters.ToArray())));
							string completedHandlerName = string.Format("client_{0}Completed", methContract.Name);
							string completedEventName = string.Format("{0}Completed", methContract.Name);
							tryClientCall.TryStatements.Add(
								new CodeAttachEventStatement(
									new CodeEventReferenceExpression(
										new CodeVariableReferenceExpression("client"),
										completedEventName),
									new CodeMethodReferenceExpression(
										new CodeThisReferenceExpression(),
										completedHandlerName)));
							#region Completed Handler
							CodeMemberMethod completedHandler = new CodeMemberMethod();
							completedHandler.Name = completedHandlerName;
							completedHandler.Attributes = MemberAttributes.Final | MemberAttributes.Private;
							completedHandler.ReturnType = new CodeTypeReference(typeof(void));
							completedHandler.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
							completedHandler.Parameters.Add(new CodeParameterDeclarationExpression(string.Format("{0}.{1}EventArgs", contractnspace, completedEventName), "e"));
							completedHandler.Statements.Add(
								new CodeVariableDeclarationStatement(
									typeof(LogicalAsyncState),
									"state",
									new CodeCastExpression(
										typeof(LogicalAsyncState),
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression(
												"e"),
												"UserState"))));
							if ( currentSvcGenType != ServiceGenerationType.HumanActivityService ) {
								#region Initialize Output Mapping Xml Document
								completedHandler.Statements.Add(	// MemoryStream msResult = new MemoryStream();
									new CodeVariableDeclarationStatement(
										typeof(MemoryStream),
										"msResult",
										new CodeObjectCreateExpression(typeof(MemoryStream))));
								completedHandler.Statements.Add(	//XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(msResult);
									new CodeVariableDeclarationStatement(
										typeof(XmlDictionaryWriter),
										"xdw",
										new CodeMethodInvokeExpression(
											new CodeTypeReferenceExpression(typeof(XmlDictionaryWriter)),
											"CreateTextWriter",
											new CodeVariableReferenceExpression("msResult"))));
								completedHandler.Statements.Add(	// xdw.WriteStartDocument();
									new CodeMethodInvokeExpression(
										new CodeVariableReferenceExpression("xdw"),
										"WriteStartDocument"));
								#endregion
							}
							string[] typenames = null;
							string[] varnames = null;
							string[] typename = null;
							string[] wrapper = null;
							//bool isCallback;
							if ( wmCallback != null ) {
								//isCallback = true;
								typenames = wmCallback.OutputTypeName.Split(';');
								varnames = wmCallback.OutputVariableName.Split(';');
								wrapper = wmCallback.OutputWrapperName.Split(':');
							} else {
								//isCallback = false;
								typenames = webmeth.OutputTypeName.Split(';');
								varnames = webmeth.OutputVariableName.Split(';');
								typename = webmeth.OutputTypeName.Split('.');
								wrapper = webmeth.OutputWrapperName.Split(':');
							}
							if ( !logact.LogicalMethod.UseOutputCodeMapping ) {
								for ( int i = 0; i < typesWSOutput.Count; i++ ) {
									string[] elements = varnames[i].Split('/');
									if ( currentSvcGenType != ServiceGenerationType.HumanActivityService ) {
										foreach ( string element in elements ) {
											completedHandler.Statements.Add(	// xdw.WriteStartElement("OUTPUTVARNAME");
												new CodeMethodInvokeExpression(
													new CodeVariableReferenceExpression("xdw"),
													"WriteStartElement",
													new CodePrimitiveExpression(element),
													new CodePrimitiveExpression(websvc.Namespace)));
										}
									}
									if ( typesWSOutput[i].GetCustomAttributes(typeof(DataContractAttribute), true).Length > 0 ||
										 typesWSOutput[i].GetCustomAttributes(typeof(CollectionDataContractAttribute), true).Length > 0 ) {
										#region Add WCF Data Contract to Output Mapping Xml Document
										// DataContractSerializer dcsResult = new DataContractSerializer(typeof(OUTPUTTYPEFULLNAME));
										completedHandler.Statements.Add(
											new CodeVariableDeclarationStatement(
												typeof(DataContractSerializer),
												"dcsResult",
												new CodeObjectCreateExpression(
													typeof(DataContractSerializer),
													new CodeTypeOfExpression(typesWSOutput[i]))));
										completedHandler.Statements.Add(	// dcsResult.WriteObjectContent(xdw, outputWS);
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("dcsResult"),
												"WriteObjectContent",
												new CodeVariableReferenceExpression("xdw"),
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("e"),
													"Result")));
										#endregion
									} else {
										#region Add Xml Serializable or Simple Type to Output Mapping Xml Document
										//XmlSerializer xsResult = new XmlSerializer(typeof(BudgetOuputDoc));
										completedHandler.Statements.Add(
											new CodeVariableDeclarationStatement(
												typeof(XmlSerializer),
												"xsResult",
												new CodeObjectCreateExpression(
													typeof(XmlSerializer),
													new CodeTypeOfExpression(typesWSOutput[i]))));
										//MemoryStream msX = new MemoryStream();
										completedHandler.Statements.Add(
											new CodeVariableDeclarationStatement(
												typeof(MemoryStream),
												"msSerialized",
												new CodeObjectCreateExpression(typeof(MemoryStream))));
										//xsResult.Serialize(msSerialized, _outputWSX);
										completedHandler.Statements.Add(
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("xsResult"),
												"Serialize",
												new CodeVariableReferenceExpression("msSerialized"),
											new CodePropertyReferenceExpression(
												new CodeVariableReferenceExpression("e"),
												"Result")));
										//msSerialized.Position = 0;
										completedHandler.Statements.Add(
											new CodeAssignStatement(
												new CodePropertyReferenceExpression(
													new CodeVariableReferenceExpression("msSerialized"),
													"Position"),
												new CodePrimitiveExpression(0)));
										//XmlDocument xdSerialized = new XmlDocument();
										completedHandler.Statements.Add(
											new CodeVariableDeclarationStatement(
												typeof(XmlDocument),
												"xdSerialized",
												new CodeObjectCreateExpression(typeof(XmlDocument))));
										//xdSerialized.Load(msSerialized);
										completedHandler.Statements.Add(
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("xdSerialized"),
												"Load",
												new CodeVariableReferenceExpression("msSerialized")));
										// msSerialized.Close();
										completedHandler.Statements.Add(
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("msSerialized"),
												"Close"));
										if ( currentSvcGenType != ServiceGenerationType.HumanActivityService ) {
											//xdw.WriteRaw(xdSerialized.DocumentElement.InnerXml);
											completedHandler.Statements.Add(
												new CodeMethodInvokeExpression(
													new CodeVariableReferenceExpression("xdw"),
													"WriteRaw",
													new CodePropertyReferenceExpression(
														new CodePropertyReferenceExpression(
															new CodeVariableReferenceExpression("xdSerialized"),
															"DocumentElement"),
														"InnerXml")));
										}
										#endregion
									}
								}
							}
							if ( currentSvcGenType == ServiceGenerationType.HumanActivityService ) {
								#region Return Human Activity Output
								completedHandler.Statements.Add(	// return OpenComposite.Orchestration.Mapping.ActOutMapping(xdSerialized);
								new CodeMethodReturnStatement(
									new CodeMethodInvokeExpression(
										mapoutTargetObj,
										methOutMap.Name,
										new CodeArgumentReferenceExpression("xdSerialized"))));
								#endregion
							} else {
								#region Complete and Return Output Mapping Xml Document
								if ( !logact.LogicalMethod.UseOutputCodeMapping ) {
									if ( !string.IsNullOrEmpty(webmeth.OutputVariableName) ) {
										for ( int i = 0; i < typesWSOutput.Count; i++ ) {
											string[] elements = varnames[i].Split('/');
											for ( int j = 0; j < elements.Length; j++ ) {
												completedHandler.Statements.Add(	// xdw.WriteEndElement();
													new CodeMethodInvokeExpression(
														new CodeVariableReferenceExpression("xdw"),
														"WriteEndElement"));
											}
										}
									}
									//if ( wrapper.Length > 0 && !string.IsNullOrEmpty(wrapper[wrapper.Length - 1]) ) {
									//    methSvcCall.Statements.Add(	// xdw.WriteEndElement();
									//        new CodeMethodInvokeExpression(
									//            new CodeVariableReferenceExpression("xdw"),
									//            "WriteEndElement"));
									//}
									completedHandler.Statements.Add(	// xdw.WriteEndDocument();
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("xdw"),
											"WriteEndDocument"));
									completedHandler.Statements.Add(	// xdw.Flush();
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("xdw"),
											"Flush"));
									completedHandler.Statements.Add(	// msResult.Position = 0;
										new CodeAssignStatement(
											new CodePropertyReferenceExpression(
												new CodeVariableReferenceExpression("msResult"),
												"Position"),
											new CodePrimitiveExpression(0)));
									completedHandler.Statements.Add(	// XmlDocument xdResult = new XmlDocument();
										new CodeVariableDeclarationStatement(
											typeof(XmlDocument),
											"xdResult",
											new CodeObjectCreateExpression(typeof(XmlDocument))));
									completedHandler.Statements.Add(	// xdResult.Load(msResult);
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("xdResult"),
											"Load",
											new CodeVariableReferenceExpression("msResult")));
									completedHandler.Statements.Add(	// xdw.Close();
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("xdw"),
											"Close"));
									completedHandler.Statements.Add(	// msResult.Close();
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("msResult"),
											"Close"));
								}
								#endregion

								// state.Output = OpenComposite.Orchestration.Mapping.ActOutMapping(xdResult);
								completedHandler.Statements.Add(
									new CodeAssignStatement(
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression("state"),
											"Output"),
										new CodeMethodInvokeExpression(
											mapoutTargetObj,
											methOutMap.Name,
											new CodeArgumentReferenceExpression(logact.LogicalMethod.UseOutputCodeMapping ? "result" : "xdResult"))));
								// state.WorkflowInstance.EnqueueItem(state.WorkflowQueueName, state, null, null);
								completedHandler.Statements.Add(
									new CodeMethodInvokeExpression(
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression("state"),
											"WorkflowInstance"),
										"EnqueueItem",
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression("state"),
											"WorkflowQueueName"),
										new CodeVariableReferenceExpression("state"),
										new CodePrimitiveExpression(null),
										new CodePrimitiveExpression(null)));
							}
							//completedHandler.Statements.Add(
							//    new CodeMethodInvokeExpression(
							//        null,
							//        string.Format("{0}CompletedCallback", methContract.Name),
							//        new CodeVariableReferenceExpression("state")));
							ctdServices.Members.AddDistinctByName(completedHandler);
							#endregion
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("client"),
									string.Format("{0}Async", methContract.Name),
									parameters.ToArray()));
							//completedHandler.Statements.Add(
						} else if ( hasOutput && wmCallback == null && hasInput ) {
							CodeExpression[] parameters = new CodeExpression[typesWSInput.Count];
							for ( int i = 0; i < typesWSInput.Count; i++ ) {
								parameters[i] = new CodeVariableReferenceExpression("inputWS" + i.ToString());
							}
							tryClientCall.TryStatements.Add(
								new CodeAssignStatement(
									new CodeVariableReferenceExpression("outputWS"),
									new CodeMethodInvokeExpression(
										clientObject,
										methContract.Name,
										parameters)));
						} else if ( hasOutput && wmCallback == null ) {
							tryClientCall.TryStatements.Add(
								new CodeAssignStatement(
									new CodeVariableReferenceExpression("outputWS"),
									new CodeMethodInvokeExpression(
										clientObject,
										methContract.Name)));
						} else if ( hasInput ) {
							CodeExpression[] parameters = new CodeExpression[typesWSInput.Count];
							for ( int i = 0; i < typesWSInput.Count; i++ ) {
								parameters[i] = new CodeVariableReferenceExpression("inputWS" + i.ToString());
							}
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									clientObject,
									methContract.Name,
									parameters));
						} else {
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									clientObject,
									methContract.Name));
						}
						if ( wmCallback != null ) {
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeFieldReferenceExpression(
										new CodeThisReferenceExpression(), fieldnameWaitOutput),
									"WaitOne"));
						}
						if ( generateAsyncInvoke && hasOutput ) {
						} else {
							tryClientCall.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("client"),
									"Close"));
						}
						CreateCatchClause(tryClientCall, "timeProblem", "The service operation timed out. ",
							typeof(TimeoutException));
						CreateCatchClause(tryClientCall, "unknownFault", "An unknown exception was received. ",
							typeof(FaultException));
						CreateCatchClause(tryClientCall, "commProblem", "There was a communication problem. ",
							typeof(CommunicationException));
						CreateCatchClause(tryClientCall, "ex", "Generic Exception. ",
							typeof(Exception));

						methSvcCall.Statements.Add(tryClientCall);
						#endregion
					}
				}
				#endregion

				#region Do Output Mapping and Return Result
				if ( methOutMap != null && !generateAsyncInvoke ) {
					string[] typenames = null;
					string[] varnames = null;
					string[] typename = null;
					string[] wrapper = null;
					bool isCallback;
					if ( wmCallback != null ) {
						isCallback = true;
						typenames = wmCallback.OutputTypeName.Split(';');
						varnames = wmCallback.OutputVariableName.Split(';');
						wrapper = wmCallback.OutputWrapperName.Split(':');
					} else if ( receiveMsmq != null ) {
						isCallback = false;
						typenames = new string[] { "System.Object" };
						varnames = new string[] { "obj" };

					} else {
						isCallback = false;
						typenames = webmeth.OutputTypeName.Split(';');
						varnames = webmeth.OutputVariableName.Split(';');
						typename = webmeth.OutputTypeName.Split('.');
						wrapper = webmeth.OutputWrapperName.Split(':');
					}
					//OLD: websvc.Name + "Contract." + websvc.Name + "Client");
					if ( currentSvcGenType != ServiceGenerationType.HumanActivityService &&
						 currentSvcGenType != ServiceGenerationType.MessageQueueService ) {
						#region Initialize Output Mapping Xml Document
						if ( !logact.LogicalMethod.UseOutputCodeMapping ) {
							methSvcCall.Statements.Add(	// MemoryStream msResult = new MemoryStream();
								new CodeVariableDeclarationStatement(
									typeof(MemoryStream),
									"msResult",
									new CodeObjectCreateExpression(typeof(MemoryStream))));
							methSvcCall.Statements.Add(	//XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(msResult);
								new CodeVariableDeclarationStatement(
									typeof(XmlDictionaryWriter),
									"xdw",
									new CodeMethodInvokeExpression(
										new CodeTypeReferenceExpression(typeof(XmlDictionaryWriter)),
										"CreateTextWriter",
										new CodeVariableReferenceExpression("msResult"))));
							methSvcCall.Statements.Add(	// xdw.WriteStartDocument();
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("xdw"),
									"WriteStartDocument"));
						}
						//if ( wrapper.Length > 0 && !string.IsNullOrEmpty(wrapper[wrapper.Length - 1]) ) {
						//    methSvcCall.Statements.Add(	// xdw.WriteStartElement("WRAPPERNAME");
						//        new CodeMethodInvokeExpression(
						//            new CodeVariableReferenceExpression("xdw"),
						//            "WriteStartElement",
						//            new CodePrimitiveExpression(wrapper[wrapper.Length - 1]),
						//            new CodePrimitiveExpression(websvc.Namespace)));
						//}
						//if ( !string.IsNullOrEmpty(webmeth.OutputVariableName) ) {
						//if ( varnames != null && varnames.Length > 0 ) {
						//    for ( int i = 0; i < varnames.Length; i++ ) {
						//        if ( isCallback ) {
						//        } else {
						//        }
						//    }
						//    methSvcCall.Statements.Add(	// xdw.WriteStartElement("OUTPUTVARNAME");
						//        new CodeMethodInvokeExpression(
						//            new CodeVariableReferenceExpression("xdw"),
						//            "WriteStartElement",
						//            new CodePrimitiveExpression(webmeth.OutputVariableName),
						//            new CodePrimitiveExpression(websvc.Namespace)));
						//}
						#endregion
					}
					if ( typesWSOutput != null ) {
						#region XSLT Mapping
						if ( logact == null || !logact.LogicalMethod.ExtendedProperties.UseOutputCodeMapping ) {
							for ( int i = 0; i < typesWSOutput.Count; i++ ) {
								string[] elements = varnames[i].Split('/');
								if ( currentSvcGenType != ServiceGenerationType.HumanActivityService ) {
									foreach ( string element in elements ) {
										methSvcCall.Statements.Add(	// xdw.WriteStartElement("OUTPUTVARNAME");
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("xdw"),
												"WriteStartElement",
												new CodePrimitiveExpression(element),
												new CodePrimitiveExpression(websvc.Namespace)));
									}
								}
								if ( typesWSOutput[i].GetCustomAttributes(typeof(DataContractAttribute), true).Length > 0 ||
									 typesWSOutput[i].GetCustomAttributes(typeof(CollectionDataContractAttribute), true).Length > 0 ) {
									#region Add WCF Data Contract to Output Mapping Xml Document
									// DataContractSerializer dcsResult = new DataContractSerializer(typeof(OUTPUTTYPEFULLNAME));
									methSvcCall.Statements.Add(
										new CodeVariableDeclarationStatement(
											typeof(DataContractSerializer),
											"dcsResult",
											new CodeObjectCreateExpression(
												typeof(DataContractSerializer),
												new CodeTypeOfExpression(typesWSOutput[i]))));
									if ( currentSvcGenType == ServiceGenerationType.SystemWebService ) {
										methSvcCall.Statements.Add(	// dcsResult.WriteObjectContent(xdw, outputWS);
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("dcsResult"),
												"WriteObjectContent",
												new CodeVariableReferenceExpression("xdw"),
												new CodeFieldReferenceExpression(null, fieldnameWSOutput)));
									} else {
										methSvcCall.Statements.Add(	// dcsResult.WriteObjectContent(xdw, outputWS);
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("dcsResult"),
												"WriteObjectContent",
												new CodeVariableReferenceExpression("xdw"),
												new CodeVariableReferenceExpression(
													isCallback ? fieldnameWSOutput + i.ToString() : fieldnameWSOutput)));
									}
									#endregion
								} else {
									#region Add Xml Serializable or Simple Type to Output Mapping Xml Document
									//XmlSerializer xsResult = new XmlSerializer(typeof(BudgetOuputDoc));
									methSvcCall.Statements.Add(
										new CodeVariableDeclarationStatement(
											typeof(XmlSerializer),
											"xsResult",
											new CodeObjectCreateExpression(
												typeof(XmlSerializer),
												new CodeTypeOfExpression(typesWSOutput[i]))));
									//MemoryStream msX = new MemoryStream();
									methSvcCall.Statements.Add(
										new CodeVariableDeclarationStatement(
											typeof(MemoryStream),
											"msSerialized",
											new CodeObjectCreateExpression(typeof(MemoryStream))));
									if ( currentSvcGenType == ServiceGenerationType.SystemWebService ) {
										//xsResult.Serialize(msSerialized, _outputWSX);
										methSvcCall.Statements.Add(
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("xsResult"),
												"Serialize",
												new CodeVariableReferenceExpression("msSerialized"),
												new CodeFieldReferenceExpression(null, fieldnameWSOutput)));
									} else {
										//xsResult.Serialize(msSerialized, outputWS);
										methSvcCall.Statements.Add(
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("xsResult"),
												"Serialize",
												new CodeVariableReferenceExpression("msSerialized"),
												new CodeVariableReferenceExpression(
													isCallback ? fieldnameWSOutput + i.ToString() : fieldnameWSOutput)));
									}
									//msSerialized.Position = 0;
									methSvcCall.Statements.Add(
										new CodeAssignStatement(
											new CodePropertyReferenceExpression(
												new CodeVariableReferenceExpression("msSerialized"),
												"Position"),
											new CodePrimitiveExpression(0)));
									//XmlDocument xdSerialized = new XmlDocument();
									methSvcCall.Statements.Add(
										new CodeVariableDeclarationStatement(
											typeof(XmlDocument),
											"xdSerialized",
											new CodeObjectCreateExpression(typeof(XmlDocument))));
									//xdSerialized.Load(msSerialized);
									methSvcCall.Statements.Add(
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("xdSerialized"),
											"Load",
											new CodeVariableReferenceExpression("msSerialized")));
									// msSerialized.Close();
									methSvcCall.Statements.Add(
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("msSerialized"),
											"Close"));
									if ( currentSvcGenType != ServiceGenerationType.HumanActivityService ) {
										//xdw.WriteRaw(xdSerialized.DocumentElement.InnerXml);
										methSvcCall.Statements.Add(
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("xdw"),
												"WriteRaw",
												new CodePropertyReferenceExpression(
													new CodePropertyReferenceExpression(
														new CodeVariableReferenceExpression("xdSerialized"),
														"DocumentElement"),
													"InnerXml")));
									}
									#endregion
								}
							}
						}
						#endregion
					}
					if ( logact != null && logact.LogicalMethod.ExtendedProperties.UseOutputCodeMapping ) {
						methSvcCall.Statements.Add(
							new CodeMethodReturnStatement(
								new CodeMethodInvokeExpression(
									mapoutTargetObj,
									methOutMap.Name,
									new CodeVariableReferenceExpression("outputWS"))));
					} else {
						if ( currentSvcGenType == ServiceGenerationType.HumanActivityService ) {
							#region Return Human Activity Output
							methSvcCall.Statements.Add(	// return OpenComposite.Orchestration.Mapping.ActOutMapping(xdSerialized);
								new CodeMethodReturnStatement(
									new CodeMethodInvokeExpression(
										mapoutTargetObj,
										methOutMap.Name,
										new CodeArgumentReferenceExpression("xdSerialized"))));
							#endregion
						} else {
							#region Complete and Return Output Mapping Xml Document
							if ( !string.IsNullOrEmpty(webmeth.OutputVariableName) ) {
								for ( int i = 0; i < typesWSOutput.Count; i++ ) {
									string[] elements = varnames[i].Split('/');
									for ( int j = 0; j < elements.Length; j++ ) {
										methSvcCall.Statements.Add(	// xdw.WriteEndElement();
											new CodeMethodInvokeExpression(
												new CodeVariableReferenceExpression("xdw"),
												"WriteEndElement"));
									}
								}
							}
							//if ( wrapper.Length > 0 && !string.IsNullOrEmpty(wrapper[wrapper.Length - 1]) ) {
							//    methSvcCall.Statements.Add(	// xdw.WriteEndElement();
							//        new CodeMethodInvokeExpression(
							//            new CodeVariableReferenceExpression("xdw"),
							//            "WriteEndElement"));
							//}
							methSvcCall.Statements.Add(	// xdw.WriteEndDocument();
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("xdw"),
									"WriteEndDocument"));
							methSvcCall.Statements.Add(	// xdw.Flush();
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("xdw"),
									"Flush"));
							methSvcCall.Statements.Add(	// msResult.Position = 0;
								new CodeAssignStatement(
									new CodePropertyReferenceExpression(
										new CodeVariableReferenceExpression("msResult"),
										"Position"),
									new CodePrimitiveExpression(0)));
							methSvcCall.Statements.Add(	// XmlDocument xdResult = new XmlDocument();
								new CodeVariableDeclarationStatement(
									typeof(XmlDocument),
									"xdResult",
									new CodeObjectCreateExpression(typeof(XmlDocument))));
							methSvcCall.Statements.Add(	// xdResult.Load(msResult);
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("xdResult"),
									"Load",
									new CodeVariableReferenceExpression("msResult")));
							methSvcCall.Statements.Add(	// xdw.Close();
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("xdw"),
									"Close"));
							methSvcCall.Statements.Add(	// msResult.Close();
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("msResult"),
									"Close"));
							methSvcCall.Statements.Add(	// return OpenComposite.Orchestration.Mapping.ActOutMapping(xdResult);
								new CodeMethodReturnStatement(
									new CodeMethodInvokeExpression(
										mapoutTargetObj,
										methOutMap.Name,
										new CodeArgumentReferenceExpression("xdResult"))));
							#endregion
						}
					}
				}
				#endregion

				#region Async msmq callback & output stuff
				//if ( generateAsyncInvoke && sendMsmq != null ) {
				//    CodeMemberMethod methCompleted = new CodeMemberMethod();
				//    methCompleted.Attributes = MemberAttributes.Private | MemberAttributes.Final;
				//    methCompleted.Name = string.Format("{0}CompletedCallback", logcap.Name);
				//    methCompleted.Parameters.Add(
				//        new CodeParameterDeclarationExpression(
				//            typeof(LogicalAsyncState),
				//            "state"));
				//    methCompleted.Statements.Add(
				//        new CodeVariableDeclarationStatement(
				//            typeof(MessageQueue),
				//            "client",
				//            new CodeCastExpression(
				//                typeof(MessageQueue),
				//                new CodePropertyReferenceExpression(
				//                    new CodeArgumentReferenceExpression("state"),
				//                    "Client"))));
				//    #region Do Output Mapping and Return Result
				//    if ( methOutMap != null && sendMsmq == null ) {
				//        string[] typenames = null;
				//        string[] varnames = null;
				//        string[] typename = null;
				//        string[] wrapper = null;
				//        //bool isCallback;
				//        if ( wmCallback != null ) {
				//            //isCallback = true;
				//            typenames = wmCallback.OutputTypeName.Split(';');
				//            varnames = wmCallback.OutputVariableName.Split(';');
				//            wrapper = wmCallback.OutputWrapperName.Split(':');
				//        } else {
				//            //isCallback = false;
				//            typenames = webmeth.OutputTypeName.Split(';');
				//            varnames = webmeth.OutputVariableName.Split(';');
				//            typename = webmeth.OutputTypeName.Split('.');
				//            wrapper = webmeth.OutputWrapperName.Split(':');
				//        }
				//        //OLD: websvc.Name + "Contract." + websvc.Name + "Client");
				//        if ( currentSvcGenType != ServiceGenerationType.HumanActivityService ) {
				//            #region Initialize Output Mapping Xml Document
				//            methCompleted.Statements.Add(	// MemoryStream msResult = new MemoryStream();
				//                new CodeVariableDeclarationStatement(
				//                    typeof(MemoryStream),
				//                    "msResult",
				//                    new CodeObjectCreateExpression(typeof(MemoryStream))));
				//            methCompleted.Statements.Add(	//XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(msResult);
				//                new CodeVariableDeclarationStatement(
				//                    typeof(XmlDictionaryWriter),
				//                    "xdw",
				//                    new CodeMethodInvokeExpression(
				//                        new CodeTypeReferenceExpression(typeof(XmlDictionaryWriter)),
				//                        "CreateTextWriter",
				//                        new CodeVariableReferenceExpression("msResult"))));
				//            methCompleted.Statements.Add(	// xdw.WriteStartDocument();
				//                new CodeMethodInvokeExpression(
				//                    new CodeVariableReferenceExpression("xdw"),
				//                    "WriteStartDocument"));
				//            #endregion
				//        }
				//        if ( typesWSOutput != null ) {
				//            if ( typesWSOutput.Count > 0 ) {
				//                methCompleted.Statements.Add(
				//                    new CodeVariableDeclarationStatement(
				//                        typesWSOutput[0],
				//                        "result",
				//                        new CodeMethodInvokeExpression(
				//                            new CodeVariableReferenceExpression("client"),
				//                            "End" + methContract.Name,
				//                            new CodePropertyReferenceExpression(
				//                                new CodeVariableReferenceExpression("state"),
				//                                "AsyncResult"))));
				//            }
				//            for ( int i = 0; i < typesWSOutput.Count; i++ ) {
				//                string[] elements = varnames[i].Split('/');
				//                if ( currentSvcGenType != ServiceGenerationType.HumanActivityService ) {
				//                    foreach ( string element in elements ) {
				//                        methCompleted.Statements.Add(	// xdw.WriteStartElement("OUTPUTVARNAME");
				//                            new CodeMethodInvokeExpression(
				//                                new CodeVariableReferenceExpression("xdw"),
				//                                "WriteStartElement",
				//                                new CodePrimitiveExpression(element),
				//                                new CodePrimitiveExpression(websvc.Namespace)));
				//                    }
				//                }
				//                if ( typesWSOutput[i].GetCustomAttributes(typeof(DataContractAttribute), true).Length > 0 ||
				//                     typesWSOutput[i].GetCustomAttributes(typeof(CollectionDataContractAttribute), true).Length > 0 ) {
				//                    #region Add WCF Data Contract to Output Mapping Xml Document
				//                    // DataContractSerializer dcsResult = new DataContractSerializer(typeof(OUTPUTTYPEFULLNAME));
				//                    methCompleted.Statements.Add(
				//                        new CodeVariableDeclarationStatement(
				//                            typeof(DataContractSerializer),
				//                            "dcsResult",
				//                            new CodeObjectCreateExpression(
				//                                typeof(DataContractSerializer),
				//                                new CodeTypeOfExpression(typesWSOutput[i]))));
				//                    methCompleted.Statements.Add(	// dcsResult.WriteObjectContent(xdw, outputWS);
				//                        new CodeMethodInvokeExpression(
				//                            new CodeVariableReferenceExpression("dcsResult"),
				//                            "WriteObjectContent",
				//                            new CodeVariableReferenceExpression("xdw"),
				//                            new CodeVariableReferenceExpression("result")));
				//                    #endregion
				//                } else {
				//                    #region Add Xml Serializable or Simple Type to Output Mapping Xml Document
				//                    //XmlSerializer xsResult = new XmlSerializer(typeof(BudgetOuputDoc));
				//                    methCompleted.Statements.Add(
				//                        new CodeVariableDeclarationStatement(
				//                            typeof(XmlSerializer),
				//                            "xsResult",
				//                            new CodeObjectCreateExpression(
				//                                typeof(XmlSerializer),
				//                                new CodeTypeOfExpression(typesWSOutput[i]))));
				//                    //MemoryStream msX = new MemoryStream();
				//                    methCompleted.Statements.Add(
				//                        new CodeVariableDeclarationStatement(
				//                            typeof(MemoryStream),
				//                            "msSerialized",
				//                            new CodeObjectCreateExpression(typeof(MemoryStream))));
				//                    //xsResult.Serialize(msSerialized, _outputWSX);
				//                    methCompleted.Statements.Add(
				//                        new CodeMethodInvokeExpression(
				//                            new CodeVariableReferenceExpression("xsResult"),
				//                            "Serialize",
				//                            new CodeVariableReferenceExpression("msSerialized"),
				//                        new CodeVariableReferenceExpression("result")));
				//                    //msSerialized.Position = 0;
				//                    methCompleted.Statements.Add(
				//                        new CodeAssignStatement(
				//                            new CodePropertyReferenceExpression(
				//                                new CodeVariableReferenceExpression("msSerialized"),
				//                                "Position"),
				//                            new CodePrimitiveExpression(0)));
				//                    //XmlDocument xdSerialized = new XmlDocument();
				//                    methCompleted.Statements.Add(
				//                        new CodeVariableDeclarationStatement(
				//                            typeof(XmlDocument),
				//                            "xdSerialized",
				//                            new CodeObjectCreateExpression(typeof(XmlDocument))));
				//                    //xdSerialized.Load(msSerialized);
				//                    methCompleted.Statements.Add(
				//                        new CodeMethodInvokeExpression(
				//                            new CodeVariableReferenceExpression("xdSerialized"),
				//                            "Load",
				//                            new CodeVariableReferenceExpression("msSerialized")));
				//                    // msSerialized.Close();
				//                    methCompleted.Statements.Add(
				//                        new CodeMethodInvokeExpression(
				//                            new CodeVariableReferenceExpression("msSerialized"),
				//                            "Close"));
				//                    if ( currentSvcGenType != ServiceGenerationType.HumanActivityService ) {
				//                        //xdw.WriteRaw(xdSerialized.DocumentElement.InnerXml);
				//                        methCompleted.Statements.Add(
				//                            new CodeMethodInvokeExpression(
				//                                new CodeVariableReferenceExpression("xdw"),
				//                                "WriteRaw",
				//                                new CodePropertyReferenceExpression(
				//                                    new CodePropertyReferenceExpression(
				//                                        new CodeVariableReferenceExpression("xdSerialized"),
				//                                        "DocumentElement"),
				//                                    "InnerXml")));
				//                    }
				//                    #endregion
				//                }
				//            }
				//        }
				//        //CodeExpression mapoutTargetObj =
				//        //    ( methOutMap.Attributes & MemberAttributes.Static ) == MemberAttributes.Static ?
				//        //    (CodeExpression)new CodeTypeReferenceExpression(typeRefMapClass) :
				//        //    (CodeExpression)new CodePropertyReferenceExpression(
				//        //        new CodeFieldReferenceExpression(
				//        //            new CodeThisReferenceExpression(), cOrchestrationField),
				//        //        "Mapping");
				//        if ( currentSvcGenType == ServiceGenerationType.HumanActivityService ) {
				//            #region Return Human Activity Output
				//            methCompleted.Statements.Add(	// return OpenComposite.Orchestration.Mapping.ActOutMapping(xdSerialized);
				//                new CodeMethodReturnStatement(
				//                    new CodeMethodInvokeExpression(
				//                        mapoutTargetObj,
				//                        methOutMap.Name,
				//                        new CodeArgumentReferenceExpression("xdSerialized"))));
				//            #endregion
				//        } else {
				//            #region Complete and Return Output Mapping Xml Document
				//            if ( !string.IsNullOrEmpty(webmeth.OutputVariableName) ) {
				//                for ( int i = 0; i < typesWSOutput.Count; i++ ) {
				//                    string[] elements = varnames[i].Split('/');
				//                    for ( int j = 0; j < elements.Length; j++ ) {
				//                        methCompleted.Statements.Add(	// xdw.WriteEndElement();
				//                            new CodeMethodInvokeExpression(
				//                                new CodeVariableReferenceExpression("xdw"),
				//                                "WriteEndElement"));
				//                    }
				//                }
				//            }
				//            //if ( wrapper.Length > 0 && !string.IsNullOrEmpty(wrapper[wrapper.Length - 1]) ) {
				//            //    methSvcCall.Statements.Add(	// xdw.WriteEndElement();
				//            //        new CodeMethodInvokeExpression(
				//            //            new CodeVariableReferenceExpression("xdw"),
				//            //            "WriteEndElement"));
				//            //}
				//            methCompleted.Statements.Add(	// xdw.WriteEndDocument();
				//                new CodeMethodInvokeExpression(
				//                    new CodeVariableReferenceExpression("xdw"),
				//                    "WriteEndDocument"));
				//            methCompleted.Statements.Add(	// xdw.Flush();
				//                new CodeMethodInvokeExpression(
				//                    new CodeVariableReferenceExpression("xdw"),
				//                    "Flush"));
				//            methCompleted.Statements.Add(	// msResult.Position = 0;
				//                new CodeAssignStatement(
				//                    new CodePropertyReferenceExpression(
				//                        new CodeVariableReferenceExpression("msResult"),
				//                        "Position"),
				//                    new CodePrimitiveExpression(0)));
				//            methCompleted.Statements.Add(	// XmlDocument xdResult = new XmlDocument();
				//                new CodeVariableDeclarationStatement(
				//                    typeof(XmlDocument),
				//                    "xdResult",
				//                    new CodeObjectCreateExpression(typeof(XmlDocument))));
				//            methCompleted.Statements.Add(	// xdResult.Load(msResult);
				//                new CodeMethodInvokeExpression(
				//                    new CodeVariableReferenceExpression("xdResult"),
				//                    "Load",
				//                    new CodeVariableReferenceExpression("msResult")));
				//            methCompleted.Statements.Add(	// xdw.Close();
				//                new CodeMethodInvokeExpression(
				//                    new CodeVariableReferenceExpression("xdw"),
				//                    "Close"));
				//            methCompleted.Statements.Add(	// msResult.Close();
				//                new CodeMethodInvokeExpression(
				//                    new CodeVariableReferenceExpression("msResult"),
				//                    "Close"));
				//            #endregion

				//            // state.Output = OpenComposite.Orchestration.Mapping.ActOutMapping(xdResult);
				//            methCompleted.Statements.Add(
				//                new CodeAssignStatement(
				//                    new CodePropertyReferenceExpression(
				//                        new CodeVariableReferenceExpression("state"),
				//                        "Output"),
				//                    new CodeMethodInvokeExpression(
				//                        mapoutTargetObj,
				//                        methOutMap.Name,
				//                        new CodeArgumentReferenceExpression("xdResult"))));
				//            // state.WorkflowInstance.EnqueueItem(state.WorkflowQueueName, state, null, null);
				//            methCompleted.Statements.Add(
				//                new CodeMethodInvokeExpression(
				//                    new CodePropertyReferenceExpression(
				//                        new CodeVariableReferenceExpression("state"),
				//                        "WorkflowInstance"),
				//                    "EnqueueItem",
				//                    new CodePropertyReferenceExpression(
				//                        new CodeVariableReferenceExpression("state"),
				//                        "WorkflowQueueName"),
				//                    new CodeVariableReferenceExpression("state"),
				//                    new CodePrimitiveExpression(null),
				//                    new CodePrimitiveExpression(null)));
				//        }
				//    }
				//    #endregion
				//    ctdServices.Members.Add(methCompleted);
				//}
				#endregion

				#region IF generateAsyncInvoke AND hasOutput: create completed callback and do output mapping
				// now handled via EventHandler {MethodName}Completed
				//if ( generateAsyncInvoke && hasOutput && receiveMsmq == null ) {
				//    CodeMemberMethod methCompleted = new CodeMemberMethod();
				//    methCompleted.Attributes = MemberAttributes.Private | MemberAttributes.Final;
				//    methCompleted.Name = string.Format("{0}CompletedCallback", methContract.Name);
				//    methCompleted.Parameters.Add(
				//        new CodeParameterDeclarationExpression(
				//            typeof(LogicalAsyncState),
				//            "state"));
				//    methCompleted.Statements.Add(
				//        new CodeVariableDeclarationStatement(
				//            typeClient,
				//            "client",
				//            new CodeCastExpression(
				//                typeClient,
				//                new CodePropertyReferenceExpression(
				//                    new CodeArgumentReferenceExpression("state"),
				//                    "Client"))));
				//    #region Do Output Mapping and Return Result
				//    if ( methOutMap != null ) {
				//        string[] typenames = null;
				//        string[] varnames = null;
				//        string[] typename = null;
				//        string[] wrapper = null;
				//        //bool isCallback;
				//        if ( wmCallback != null ) {
				//            //isCallback = true;
				//            typenames = wmCallback.OutputTypeName.Split(';');
				//            varnames = wmCallback.OutputVariableName.Split(';');
				//            wrapper = wmCallback.OutputWrapperName.Split(':');
				//        } else {
				//            //isCallback = false;
				//            typenames = webmeth.OutputTypeName.Split(';');
				//            varnames = webmeth.OutputVariableName.Split(';');
				//            typename = webmeth.OutputTypeName.Split('.');
				//            wrapper = webmeth.OutputWrapperName.Split(':');
				//        }
				//        //OLD: websvc.Name + "Contract." + websvc.Name + "Client");
				//        if ( currentSvcGenType != ServiceGenerationType.HumanActivityService ) {
				//            #region Initialize Output Mapping Xml Document
				//            methCompleted.Statements.Add(	// MemoryStream msResult = new MemoryStream();
				//                new CodeVariableDeclarationStatement(
				//                    typeof(MemoryStream),
				//                    "msResult",
				//                    new CodeObjectCreateExpression(typeof(MemoryStream))));
				//            methCompleted.Statements.Add(	//XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(msResult);
				//                new CodeVariableDeclarationStatement(
				//                    typeof(XmlDictionaryWriter),
				//                    "xdw",
				//                    new CodeMethodInvokeExpression(
				//                        new CodeTypeReferenceExpression(typeof(XmlDictionaryWriter)),
				//                        "CreateTextWriter",
				//                        new CodeVariableReferenceExpression("msResult"))));
				//            methCompleted.Statements.Add(	// xdw.WriteStartDocument();
				//                new CodeMethodInvokeExpression(
				//                    new CodeVariableReferenceExpression("xdw"),
				//                    "WriteStartDocument"));
				//            #endregion
				//        }
				//        if ( typesWSOutput != null ) {
				//            if ( typesWSOutput.Count > 0 ) {
				//                methCompleted.Statements.Add(
				//                    new CodeVariableDeclarationStatement(
				//                        typesWSOutput[0],
				//                        "result",
				//                        new CodeMethodInvokeExpression(
				//                            new CodeVariableReferenceExpression("client"),
				//                            "End" + methContract.Name,
				//                            new CodePropertyReferenceExpression(
				//                                new CodeVariableReferenceExpression("state"),
				//                                "AsyncResult"))));
				//            }
				//            if ( !logact.LogicalMethod.UseOutputCodeMapping ) {
				//                for ( int i = 0; i < typesWSOutput.Count; i++ ) {
				//                    string[] elements = varnames[i].Split('/');
				//                    if ( currentSvcGenType != ServiceGenerationType.HumanActivityService ) {
				//                        foreach ( string element in elements ) {
				//                            methCompleted.Statements.Add(	// xdw.WriteStartElement("OUTPUTVARNAME");
				//                                new CodeMethodInvokeExpression(
				//                                    new CodeVariableReferenceExpression("xdw"),
				//                                    "WriteStartElement",
				//                                    new CodePrimitiveExpression(element),
				//                                    new CodePrimitiveExpression(websvc.Namespace)));
				//                        }
				//                    }
				//                    if ( typesWSOutput[i].GetCustomAttributes(typeof(DataContractAttribute), true).Length > 0 ||
				//                         typesWSOutput[i].GetCustomAttributes(typeof(CollectionDataContractAttribute), true).Length > 0 ) {
				//                        #region Add WCF Data Contract to Output Mapping Xml Document
				//                        // DataContractSerializer dcsResult = new DataContractSerializer(typeof(OUTPUTTYPEFULLNAME));
				//                        methCompleted.Statements.Add(
				//                            new CodeVariableDeclarationStatement(
				//                                typeof(DataContractSerializer),
				//                                "dcsResult",
				//                                new CodeObjectCreateExpression(
				//                                    typeof(DataContractSerializer),
				//                                    new CodeTypeOfExpression(typesWSOutput[i]))));
				//                        methCompleted.Statements.Add(	// dcsResult.WriteObjectContent(xdw, outputWS);
				//                            new CodeMethodInvokeExpression(
				//                                new CodeVariableReferenceExpression("dcsResult"),
				//                                "WriteObjectContent",
				//                                new CodeVariableReferenceExpression("xdw"),
				//                                new CodeVariableReferenceExpression("result")));
				//                        #endregion
				//                    } else {
				//                        #region Add Xml Serializable or Simple Type to Output Mapping Xml Document
				//                        //XmlSerializer xsResult = new XmlSerializer(typeof(BudgetOuputDoc));
				//                        methCompleted.Statements.Add(
				//                            new CodeVariableDeclarationStatement(
				//                                typeof(XmlSerializer),
				//                                "xsResult",
				//                                new CodeObjectCreateExpression(
				//                                    typeof(XmlSerializer),
				//                                    new CodeTypeOfExpression(typesWSOutput[i]))));
				//                        //MemoryStream msX = new MemoryStream();
				//                        methCompleted.Statements.Add(
				//                            new CodeVariableDeclarationStatement(
				//                                typeof(MemoryStream),
				//                                "msSerialized",
				//                                new CodeObjectCreateExpression(typeof(MemoryStream))));
				//                        //xsResult.Serialize(msSerialized, _outputWSX);
				//                        methCompleted.Statements.Add(
				//                            new CodeMethodInvokeExpression(
				//                                new CodeVariableReferenceExpression("xsResult"),
				//                                "Serialize",
				//                                new CodeVariableReferenceExpression("msSerialized"),
				//                            new CodeVariableReferenceExpression("result")));
				//                        //msSerialized.Position = 0;
				//                        methCompleted.Statements.Add(
				//                            new CodeAssignStatement(
				//                                new CodePropertyReferenceExpression(
				//                                    new CodeVariableReferenceExpression("msSerialized"),
				//                                    "Position"),
				//                                new CodePrimitiveExpression(0)));
				//                        //XmlDocument xdSerialized = new XmlDocument();
				//                        methCompleted.Statements.Add(
				//                            new CodeVariableDeclarationStatement(
				//                                typeof(XmlDocument),
				//                                "xdSerialized",
				//                                new CodeObjectCreateExpression(typeof(XmlDocument))));
				//                        //xdSerialized.Load(msSerialized);
				//                        methCompleted.Statements.Add(
				//                            new CodeMethodInvokeExpression(
				//                                new CodeVariableReferenceExpression("xdSerialized"),
				//                                "Load",
				//                                new CodeVariableReferenceExpression("msSerialized")));
				//                        // msSerialized.Close();
				//                        methCompleted.Statements.Add(
				//                            new CodeMethodInvokeExpression(
				//                                new CodeVariableReferenceExpression("msSerialized"),
				//                                "Close"));
				//                        if ( currentSvcGenType != ServiceGenerationType.HumanActivityService ) {
				//                            //xdw.WriteRaw(xdSerialized.DocumentElement.InnerXml);
				//                            methCompleted.Statements.Add(
				//                                new CodeMethodInvokeExpression(
				//                                    new CodeVariableReferenceExpression("xdw"),
				//                                    "WriteRaw",
				//                                    new CodePropertyReferenceExpression(
				//                                        new CodePropertyReferenceExpression(
				//                                            new CodeVariableReferenceExpression("xdSerialized"),
				//                                            "DocumentElement"),
				//                                        "InnerXml")));
				//                        }
				//                        #endregion
				//                    }
				//                }
				//            }
				//        }
				//        //CodeExpression mapoutTargetObj =
				//        //    ( methOutMap.Attributes & MemberAttributes.Static ) == MemberAttributes.Static ?
				//        //    (CodeExpression)new CodeTypeReferenceExpression(typeRefMapClass) :
				//        //    (CodeExpression)new CodePropertyReferenceExpression(
				//        //        new CodeFieldReferenceExpression(
				//        //            new CodeThisReferenceExpression(), cOrchestrationField),
				//        //        "Mapping");
				//        if ( currentSvcGenType == ServiceGenerationType.HumanActivityService ) {
				//            #region Return Human Activity Output
				//            methCompleted.Statements.Add(	// return OpenComposite.Orchestration.Mapping.ActOutMapping(xdSerialized);
				//                new CodeMethodReturnStatement(
				//                    new CodeMethodInvokeExpression(
				//                        mapoutTargetObj,
				//                        methOutMap.Name,
				//                        new CodeArgumentReferenceExpression("xdSerialized"))));
				//            #endregion
				//        } else {
				//            #region Complete and Return Output Mapping Xml Document
				//            if ( !logact.LogicalMethod.UseOutputCodeMapping ) {
				//                if ( !string.IsNullOrEmpty(webmeth.OutputVariableName) ) {
				//                    for ( int i = 0; i < typesWSOutput.Count; i++ ) {
				//                        string[] elements = varnames[i].Split('/');
				//                        for ( int j = 0; j < elements.Length; j++ ) {
				//                            methCompleted.Statements.Add(	// xdw.WriteEndElement();
				//                                new CodeMethodInvokeExpression(
				//                                    new CodeVariableReferenceExpression("xdw"),
				//                                    "WriteEndElement"));
				//                        }
				//                    }
				//                }
				//                //if ( wrapper.Length > 0 && !string.IsNullOrEmpty(wrapper[wrapper.Length - 1]) ) {
				//                //    methSvcCall.Statements.Add(	// xdw.WriteEndElement();
				//                //        new CodeMethodInvokeExpression(
				//                //            new CodeVariableReferenceExpression("xdw"),
				//                //            "WriteEndElement"));
				//                //}
				//                methCompleted.Statements.Add(	// xdw.WriteEndDocument();
				//                    new CodeMethodInvokeExpression(
				//                        new CodeVariableReferenceExpression("xdw"),
				//                        "WriteEndDocument"));
				//                methCompleted.Statements.Add(	// xdw.Flush();
				//                    new CodeMethodInvokeExpression(
				//                        new CodeVariableReferenceExpression("xdw"),
				//                        "Flush"));
				//                methCompleted.Statements.Add(	// msResult.Position = 0;
				//                    new CodeAssignStatement(
				//                        new CodePropertyReferenceExpression(
				//                            new CodeVariableReferenceExpression("msResult"),
				//                            "Position"),
				//                        new CodePrimitiveExpression(0)));
				//                methCompleted.Statements.Add(	// XmlDocument xdResult = new XmlDocument();
				//                    new CodeVariableDeclarationStatement(
				//                        typeof(XmlDocument),
				//                        "xdResult",
				//                        new CodeObjectCreateExpression(typeof(XmlDocument))));
				//                methCompleted.Statements.Add(	// xdResult.Load(msResult);
				//                    new CodeMethodInvokeExpression(
				//                        new CodeVariableReferenceExpression("xdResult"),
				//                        "Load",
				//                        new CodeVariableReferenceExpression("msResult")));
				//                methCompleted.Statements.Add(	// xdw.Close();
				//                    new CodeMethodInvokeExpression(
				//                        new CodeVariableReferenceExpression("xdw"),
				//                        "Close"));
				//                methCompleted.Statements.Add(	// msResult.Close();
				//                    new CodeMethodInvokeExpression(
				//                        new CodeVariableReferenceExpression("msResult"),
				//                        "Close"));
				//            }
				//            #endregion

				//            // state.Output = OpenComposite.Orchestration.Mapping.ActOutMapping(xdResult);
				//            methCompleted.Statements.Add(
				//                new CodeAssignStatement(
				//                    new CodePropertyReferenceExpression(
				//                        new CodeVariableReferenceExpression("state"),
				//                        "Output"),
				//                    new CodeMethodInvokeExpression(
				//                        mapoutTargetObj,
				//                        methOutMap.Name,
				//                        new CodeArgumentReferenceExpression(logact.LogicalMethod.UseOutputCodeMapping ? "result" : "xdResult"))));
				//            // state.WorkflowInstance.EnqueueItem(state.WorkflowQueueName, state, null, null);
				//            methCompleted.Statements.Add(
				//                new CodeMethodInvokeExpression(
				//                    new CodePropertyReferenceExpression(
				//                        new CodeVariableReferenceExpression("state"),
				//                        "WorkflowInstance"),
				//                    "EnqueueItem",
				//                    new CodePropertyReferenceExpression(
				//                        new CodeVariableReferenceExpression("state"),
				//                        "WorkflowQueueName"),
				//                    new CodeVariableReferenceExpression("state"),
				//                    new CodePrimitiveExpression(null),
				//                    new CodePrimitiveExpression(null)));
				//        }
				//    }
				//    #endregion
				//    ctdServices.Members.Add(methCompleted);
				//}
				#endregion
			} else {
				methSvcCall.Statements.Add(
					new CodeCommentStatement("Add your code here"));
				methSvcCall.Statements.Add(
					new CodeThrowExceptionStatement(
						new CodeObjectCreateExpression(typeof(NotImplementedException))));
			}

			#region Add Method to ServiceCall Class and Refresh TypeProvider
			ctdServices.Members.Add(methSvcCall);
			RefreshTypeProvider(ref typeProvider, ref codeServices);
			#endregion

		}

		private static void addSplitMethod(CodeTypeDeclaration ctdServices)
		{
			bool splitMethodExists = false;
			foreach ( CodeTypeMember member in ctdServices.Members ) {
				CodeSnippetTypeMember snip = member as CodeSnippetTypeMember;
				if ( snip != null && snip.Text.Contains("splitParticipants") ) {
					splitMethodExists = true;
					break;	// CANCEL members
				}
			}
			if ( !splitMethodExists ) {
				ctdServices.Members.Add(
					new CodeSnippetTypeMember(CodeSnippets.CodeMethod_splitParticipants));
			}
		}
		private string _cInitWorkflowQueueMethodName = "initWorkflowQueue";
		private void CreateInitWorkflowQueueMethod(CodeTypeDeclaration codeClass)
		{
			foreach ( CodeTypeMember member in codeClass.Members ) {
				CodeMemberMethod method = member as CodeMemberMethod;
				if ( method != null && method.Name == _cInitWorkflowQueueMethodName ) {
					// initWorkflowQueue method exists
					return;
				}
			}
			CodeMemberMethod meth = new CodeMemberMethod();
			meth.Attributes = MemberAttributes.Private | MemberAttributes.Final;
			meth.Name = _cInitWorkflowQueueMethodName;
			meth.Parameters.Add(new CodeParameterDeclarationExpression(typeof(WorkflowQueuingService), "qservice"));
			meth.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "qname"));
			meth.ReturnType = new CodeTypeReference(typeof(WorkflowQueue));
			//WorkflowQueue wq = null;
			//if ( qservice.Exists(qname) ) {
			//    wq = qservice.GetWorkflowQueue(qname);
			//} else {
			//    wq = qservice.CreateWorkflowQueue(qname, true);
			//}
			meth.Statements.Add(
				new CodeVariableDeclarationStatement(
					typeof(WorkflowQueue), "wq",
					new CodePrimitiveExpression(null)));
			meth.Statements.Add(
				new CodeConditionStatement(
					new CodeMethodInvokeExpression(
						new CodeArgumentReferenceExpression("qservice"),
						"Exists",
						new CodeArgumentReferenceExpression("qname")),
					new CodeStatement[] {
						new CodeAssignStatement(
							new CodeVariableReferenceExpression("wq"),
							new CodeMethodInvokeExpression(
								new CodeArgumentReferenceExpression("qservice"),
								"GetWorkflowQueue",
								new CodeArgumentReferenceExpression("qname")))
					},
					new CodeStatement[] {
						new CodeAssignStatement(
							new CodeVariableReferenceExpression("wq"),
							new CodeMethodInvokeExpression(
								new CodeArgumentReferenceExpression("qservice"),
								"CreateWorkflowQueue",
								new CodeArgumentReferenceExpression("qname"),
								new CodePrimitiveExpression(true)))
					}));
			meth.Statements.Add(
				new CodeMethodReturnStatement(
					new CodeVariableReferenceExpression("wq")));

			codeClass.Members.Add(meth);
		}

		/// <summary>
		/// Implements the callback interface.
		/// </summary>
		/// <param name="ctdServices">The CTD services.</param>
		/// <param name="typeICallback">The type I callback.</param>
		internal void ImplementCallbackInterface(CodeTypeDeclaration ctdServices, Type typeICallback)
		{
			#region Is Implemented ?
			foreach ( CodeTypeReference typeRefBase in ctdServices.BaseTypes ) {
				if ( typeRefBase.BaseType == typeICallback.FullName ) {
					return;
					// RETURN
				}
			}
			#endregion

			#region Create ICallback Region	(#region / #endregion)
			CodeRegionDirective regionStart = new CodeRegionDirective(
				CodeRegionMode.Start, typeICallback.Name + " Members");
			CodeRegionDirective regionEnd = new CodeRegionDirective(
				CodeRegionMode.End, typeICallback.Name + " Members");
			#endregion

			ctdServices.BaseTypes.Add(typeICallback);

			bool startAdded = false;
			MemberInfo[] memberInfos = typeICallback.GetMembers();
			CodeMemberMethod methLast = null;
			for ( int i = 0; i < memberInfos.Length; i++ ) {
				MethodInfo methInfo = memberInfos[i] as MethodInfo;
				if ( methInfo != null ) {
					#region implement callback interface method
					CodeMemberMethod meth = new CodeMemberMethod();
					meth.Name = methInfo.Name;
					meth.Attributes = MemberAttributes.Final | MemberAttributes.Public;
					meth.ReturnType = new CodeTypeReference(methInfo.ReturnType);
					foreach ( ParameterInfo pi in methInfo.GetParameters() ) {
						meth.Parameters.Add(
							new CodeParameterDeclarationExpression(pi.ParameterType, pi.Name));
					}
					if ( !startAdded ) {
						meth.StartDirectives.Add(regionStart);
						startAdded = true;
					}

					if ( ( methInfo.Name.StartsWith("Begin") && methInfo.ReturnType == typeof(IAsyncResult) ) ||
						 ( methInfo.Name.StartsWith("End") && methInfo.GetParameters().Length == 1 &&
						   methInfo.GetParameters()[0].ParameterType == typeof(IAsyncResult) ) ) {
						// no implementation for Begin / End asynchronous methods
						meth.Statements.Add(
							new CodeThrowExceptionStatement(
								new CodeObjectCreateExpression(typeof(NotImplementedException))));
						ctdServices.Members.Add(meth);
						methLast = meth;
						continue;
						// Continue
					}
					int indexParam = 0;
					string fieldnameWSOutput = c_outputWS + methInfo.Name;
					string fieldnameWaitOutput = c_wait + methInfo.Name;
					// declare output fields
					foreach ( ParameterInfo pi in methInfo.GetParameters() ) {
						CodeMemberField fieldWSOutput = new CodeMemberField();
						fieldWSOutput.Attributes = MemberAttributes.Final | MemberAttributes.Private;
						fieldWSOutput.Name = fieldnameWSOutput + indexParam.ToString();
						fieldWSOutput.Type = new CodeTypeReference(pi.ParameterType);
						ctdServices.Members.Add(fieldWSOutput);
						meth.Statements.Add(
							new CodeAssignStatement(
								new CodeFieldReferenceExpression(
									new CodeThisReferenceExpression(), fieldWSOutput.Name),
								new CodeArgumentReferenceExpression(pi.Name)));
						indexParam++;
					}
					// create AutoResetEvent member field
					CodeMemberField fieldWait = new CodeMemberField();
					fieldWait.Attributes = MemberAttributes.Final | MemberAttributes.Private;
					fieldWait.Name = fieldnameWaitOutput;
					fieldWait.Type = new CodeTypeReference(typeof(AutoResetEvent));
					ctdServices.Members.Add(fieldWait);

					meth.Statements.Add(
						new CodeMethodInvokeExpression(
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), fieldnameWaitOutput),
							"Set"));

					ctdServices.Members.Add(meth);
					methLast = meth;
					#endregion
				}
			}
			if ( methLast != null ) {
				methLast.EndDirectives.Add(regionEnd);
			}
		}

		/// <summary>
		/// Creates the check and append part string statement.
		/// </summary>
		/// <param name="participantsVarName">Name of the participants var.</param>
		/// <param name="partStringVarName">Name of the part string var.</param>
		/// <returns></returns>
		internal CodeConditionStatement CreateCheckAndAppendPartStringStatement(
			string participantsVarName, string partStringVarName)
		{
			// if ( !string.IsNullOrEmpty(partString) ) {
			return new CodeConditionStatement(
					new CodeBinaryOperatorExpression(
						new CodeMethodInvokeExpression(
							new CodeTypeReferenceExpression(typeof(string)),
							"IsNullOrEmpty",
							new CodeVariableReferenceExpression(partStringVarName)),
					CodeBinaryOperatorType.ValueEquality,
					new CodePrimitiveExpression(false)),
				// if ( in/excludedParticipants != "" ) in/excludedParticipants += ";";
					new CodeConditionStatement(
						new CodeBinaryOperatorExpression(
							new CodeVariableReferenceExpression(participantsVarName),
							CodeBinaryOperatorType.IdentityInequality,
							new CodePrimitiveExpression("")),
						new CodeAssignStatement(
							new CodeVariableReferenceExpression(participantsVarName),
							new CodeBinaryOperatorExpression(
								new CodeVariableReferenceExpression(participantsVarName),
								CodeBinaryOperatorType.Add,
								new CodePrimitiveExpression(";")))),
				// in/excludedParticipants += partString;
					new CodeAssignStatement(
						new CodeVariableReferenceExpression(participantsVarName),
						new CodeBinaryOperatorExpression(
							new CodeVariableReferenceExpression(participantsVarName),
							CodeBinaryOperatorType.Add,
							new CodeVariableReferenceExpression(partStringVarName))));
			// }
		}

		#endregion

		#region Add Schema / Business Object Classes to Code

		/// <summary>
		/// Adds the schema classes to code namespace.
		/// </summary>
		/// <param name="codeNamespace">The code namespace.</param>
		/// <param name="schema">The schema.</param>
		internal void AddSchemaClassesToCodeNamespace(
			CodeNamespace codeNamespace, XmlSchema schema)
		{
			if ( schema == null )
				return;

			XmlSchemaSet xsdset = CreateXmlSchemaSetForDataContract();
			xsdset.Add(schema);
			// compile schema
			xsdset.Compile();
			// add classes to data code
			XmlSchemas xsds = new XmlSchemas();
			foreach ( XmlSchema xsd in xsdset.Schemas() ) {
				xsds.Add(xsd);
			}
			xsds.Compile(null, true);
			XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds);

			CodeNamespace codeNSNew = new CodeNamespace(codeNamespace.Name);
			XmlCodeExporter codeExporter = new XmlCodeExporter(codeNSNew);
			List<XmlTypeMapping> maps = new List<XmlTypeMapping>();

			foreach ( XmlSchema xsd in xsds ) {
				foreach ( XmlSchemaType schemaType in xsd.SchemaTypes.Values ) {
					maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName));
				}
				foreach ( XmlSchemaElement schemaElement in xsd.Elements.Values ) {
					maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName));
				}
			}
			foreach ( XmlTypeMapping map in maps ) {
				codeExporter.ExportTypeMapping(map);
			}

			// create the codedom
			foreach ( CodeTypeDeclaration typeNew in codeNSNew.Types ) {
				bool bFound = false;
				foreach ( CodeTypeDeclaration type in codeNamespace.Types ) {
					if ( type.Name == typeNew.Name ) {
						bFound = true;
						break;
					}
				}
				if ( !bFound ) {
					codeNamespace.Types.Add(typeNew);
				}
			}
		}
		/// <summary>
		/// Adds the schema classes to data code.
		/// </summary>
		/// <param name="codeData">The code data.</param>
		/// <param name="namespaceData">The namespace data.</param>
		/// <param name="typeProvider">The type provider.</param>
		/// <param name="xsd">The XSD.</param>
		internal void AddSchemaClassesToDataCode(
			CodeCompileUnit codeData, string namespaceData, TypeProvider typeProvider, XmlSchema xsd, BusinessObject businessObject)
		{
			if ( xsd == null )
				return;

			XmlSchemaSet xsdset = CreateXmlSchemaSetForDataContract();
			xsdset.Add(xsd);
			// compile schema
			xsdset.Compile();
			// add classes to data code
			AddXmlClassesToDataCode(codeData, namespaceData, xsdset, businessObject);
			// refresh typeProvider
			if ( typeProvider != null ) {
				RefreshTypeProvider(ref typeProvider, ref codeData);
			}
		}
		/// <summary>
		/// Adds the data contracts to data code.
		/// </summary>
		/// <param name="codeData">The code data.</param>
		/// <param name="namespaceData">The namespace data.</param>
		/// <param name="xsdset">The xsdset.</param>
		internal void AddDataContractsToDataCode(
			CodeCompileUnit codeData, string namespaceData, XmlSchemaSet xsdset, BusinessObject businessObject)
		{
			XsdDataContractImporter importer = new XsdDataContractImporter();
			importer.Options = new ImportOptions();
			importer.Options.Namespaces.Add("*", namespaceData);
			importer.Options.GenerateSerializable = true;
			//importer.Options.DataContractSurrogate
			importer.Import(xsdset);

			foreach ( CodeNamespace codeNs in importer.CodeCompileUnit.Namespaces ) {
				foreach ( CodeTypeDeclaration codetypeNew in codeNs.Types ) {
					if ( codeData.Namespaces[0].Name == codeNs.Name ) {
						bool bExists = false;
						foreach ( CodeTypeDeclaration codetypeExisting in codeData.Namespaces[0].Types ) {
							if ( codetypeExisting.Name == codetypeNew.Name ) {
								bExists = true;
								break;
							}
						}
						if ( !bExists ) {
							foreach ( CodeTypeMember member in codetypeNew.Members ) {
								if ( (int)member.Attributes == 20482 ) {
									foreach ( BusinessObjectField field in businessObject.BusinessObjectFields ) {
										if ( field.BusinessObject == null ) continue;
										if ( field.BusinessObject.Name == member.Name ||
											string.Format("{0}Type", field.BusinessObject) == member.Name ) {
											member.CustomAttributes.Add(new CodeAttributeDeclaration(
												new CodeTypeReference(typeof(RepositoryInformationAttribute)),
													new CodeAttributeArgument(
														new CodePrimitiveExpression(field.BusinessObject.ID)),
													new CodeAttributeArgument(
														new CodePrimitiveExpression(field.BusinessObject.Name)),
													new CodeAttributeArgument(
														new CodePrimitiveExpression(field.BusinessObject.RepositoryItemTypeName))));
										}
										break;
									}
								}
							}
							BusinessObject bo = businessObject;
							if ( bo.Name != codetypeNew.Name ) {
								foreach ( BusinessObjectField field in bo.BusinessObjectFields ) {
									if ( field.BusinessObject == null ) continue;
									if ( field.BusinessObject.Name == codetypeNew.Name ) {
										bo = field.BusinessObject;
										break;
									}
								}
							}
							codetypeNew.CustomAttributes.Add(
								new CodeAttributeDeclaration(
									new CodeTypeReference(typeof(RepositoryInformationAttribute)),
										new CodeAttributeArgument(
											new CodePrimitiveExpression(bo.ID)),
										new CodeAttributeArgument(
											new CodePrimitiveExpression(bo.Name)),
										new CodeAttributeArgument(
											new CodePrimitiveExpression(bo.RepositoryItemTypeName))));
							codeData.Namespaces[0].Types.Add(codetypeNew);
						}
					}
				}
			}
		}
		/// <summary>
		/// Adds the XML classes to data code.
		/// </summary>
		/// <param name="codeData">The code data.</param>
		/// <param name="namespaceData">The namespace data.</param>
		/// <param name="xsdset">The xsdset.</param>
		internal void AddXmlClassesToDataCode(
			CodeCompileUnit codeData, string namespaceData, XmlSchemaSet xsdset, BusinessObject businessObject)
		{
			XmlSchemas xsds = new XmlSchemas();
			foreach ( XmlSchema xsd in xsdset.Schemas() ) {
				xsds.Add(xsd);
			}
			xsds.Compile(null, true);
			XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds);

			CodeNamespace codeNSNew = new CodeNamespace(namespaceData);
			XmlCodeExporter codeExporter = new XmlCodeExporter(codeNSNew);
			List<XmlTypeMapping> maps = new List<XmlTypeMapping>();

			foreach ( XmlSchema xsd in xsds ) {
				foreach ( XmlSchemaType schemaType in xsd.SchemaTypes.Values ) {
					maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName));
				}
				foreach ( XmlSchemaElement schemaElement in xsd.Elements.Values ) {
					maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName));
				}
			}
			foreach ( XmlTypeMapping map in maps ) {
				codeExporter.ExportTypeMapping(map);
			}

			// create the codedom
			CodeNamespace codeNamespace = null;
			foreach ( CodeNamespace codens in codeData.Namespaces ) {
				if ( codens.Name == namespaceData ) {
					codeNamespace = codens;
					break;
				}
			}
			if ( codeNamespace == null ) {
				codeNamespace = new CodeNamespace(namespaceData);
				codeData.Namespaces.Add(codeNamespace);
			}
			foreach ( CodeTypeDeclaration typeNew in codeNSNew.Types ) {
				bool bFound = false;
				foreach ( CodeTypeDeclaration type in codeNamespace.Types ) {
					if ( type.Name == typeNew.Name ) {
						bFound = true;
						break;
					}
				}
				if ( !bFound ) {
					foreach ( CodeTypeMember member in typeNew.Members ) {
						if ( (int)member.Attributes == 20482 ) {
							foreach ( BusinessObjectField field in businessObject.BusinessObjectFields ) {
								if ( field.BusinessObject == null ) continue;
								if ( field.BusinessObject.Name == member.Name ||
									string.Format("{0}Type", field.BusinessObject) == member.Name ) {
									member.CustomAttributes.Add(new CodeAttributeDeclaration(
										new CodeTypeReference(typeof(RepositoryInformationAttribute)),
											new CodeAttributeArgument(
												new CodePrimitiveExpression(field.BusinessObject.ID)),
											new CodeAttributeArgument(
												new CodePrimitiveExpression(field.BusinessObject.Name)),
											new CodeAttributeArgument(
												new CodePrimitiveExpression(field.BusinessObject.RepositoryItemTypeName))));
								}
								break;
							}
						}
					}
					BusinessObject bo = businessObject;
					if ( bo.Name != typeNew.Name ) {
						foreach ( BusinessObjectField field in bo.BusinessObjectFields ) {
							if ( field.BusinessObject == null ) continue;
							if ( field.BusinessObject.Name == typeNew.Name ) {
								bo = field.BusinessObject;
								break;
							}
						}
					}
					if ( typeNew.Name.Contains(bo.Name) ) {
						typeNew.CustomAttributes.Add(
							new CodeAttributeDeclaration(
								new CodeTypeReference(typeof(RepositoryInformationAttribute)),
									new CodeAttributeArgument(
										new CodePrimitiveExpression(bo.ID)),
									new CodeAttributeArgument(
										new CodePrimitiveExpression(bo.Name)),
									new CodeAttributeArgument(
										new CodePrimitiveExpression(bo.RepositoryItemTypeName))));
					}
					codeNamespace.Types.Add(typeNew);
				}
			}

			////RemoveAttributes(codeNamespace);

			//// Check for invalid characters in identifiers
			//CodeGenerator.ValidateIdentifiers(codeNamespace);

			//// output the C# code
			//CSharpCodeProvider codeProvider = new CSharpCodeProvider();

			//using ( StringWriter writer = new StringWriter() ) {
			//    codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions());
			//    Console.WriteLine(writer.GetStringBuilder().ToString());
			//}

			//Console.ReadLine();
		}
		/// <summary>
		/// Adds the business object to data code.
		/// </summary>
		/// <param name="codeData">The code data.</param>
		/// <param name="namespaceData">The namespace data.</param>
		/// <param name="typeProvider">The type provider.</param>
		/// <param name="businessObject">The business object.</param>
		/// <param name="generateDataContract">if set to <c>true</c> [generate data contract].</param>
		internal void AddBusinessObjectToDataCode(
			CodeCompileUnit codeData, string namespaceData, TypeProvider typeProvider,
			BusinessObject businessObject, bool generateDataContract)
		{
			if ( businessObject == null ) {
				return; throw new ArgumentNullException("businessObject");
			}
			if ( businessObject.Schema == null ) {
				throw new NullReferenceException(
					string.Format("The business object \"{0}\" contains no schema.", businessObject.Name));
			}
			try {
				XmlSchemaSet xsdset = CreateXmlSchemaSetForDataContract();
				xsdset.Add(businessObject.Schema);
				// compile schema
				xsdset.Compile();
				if ( generateDataContract ) {
					AddDataContractsToDataCode(codeData, namespaceData, xsdset, businessObject);
				} else {
					AddXmlClassesToDataCode(codeData, namespaceData, xsdset, businessObject);
				}
			} catch ( Exception ex ) {
				throw new Exception(
					string.Format("Error in Business Object \"{0}\".{1}{1}{2}",
								  businessObject.Name, Environment.NewLine, ex.Message),
					ex);
			}
			// refresh typeProvider
			if ( typeProvider != null ) RefreshTypeProvider(ref typeProvider, ref codeData);
		}
		/// <summary>
		/// Creates the XML schema set for data contract.
		/// </summary>
		/// <returns></returns>
		internal XmlSchemaSet CreateXmlSchemaSetForDataContract()
		{
			XsdDataContractExporter ex = new XsdDataContractExporter();
			ex.Export(typeof(OpenComposite.EII.Designer.Workflow.Help));
			XmlSchemaSet xsdset = ex.Schemas;
			XmlSchema xsdRemove = null;
			foreach ( XmlSchema xsd in xsdset.Schemas() ) {
				if ( xsd.Elements.Contains(new XmlQualifiedName("Help", xsd.TargetNamespace)) ) {
					xsdRemove = xsd;
				}
			}
			xsdset.Remove(xsdRemove);
			return xsdset;
		}

		#endregion

		#region Contract

		/// <summary>
		/// Generates the web method contract.
		/// </summary>
		/// <param name="currentSvcGenType">Type of the current SVC gen.</param>
		/// <param name="typeProvider">The type provider.</param>
		/// <param name="typeRefLogActContract">The type ref log act contract.</param>
		/// <param name="webmeth">The webmeth.</param>
		/// <param name="webmethResult">The webmeth result.</param>
		/// <param name="websvc">The websvc.</param>
		/// <param name="contractnspace">The contractnspace.</param>
		/// <param name="wsdl">The WSDL.</param>
		/// <param name="bindings">The bindings.</param>
		/// <param name="logact">The logact.</param>
		/// <param name="endpointConfigName">Name of the endpoint config.</param>
		/// <param name="configuration">The configuration.</param>
		/// <param name="codeContracts">The code contracts.</param>
		internal void GenerateWebMethodContract(
			ServiceGenerationType currentSvcGenType, ref TypeProvider typeProvider,
			ref CodeTypeReference typeRefLogActContract, Repository.WebService websvc,
			ref string contractnspace, ref System.Web.Services.Description.ServiceDescription wsdl,
			ref Collection<System.ServiceModel.Channels.Binding> bindings,
			Repository.LogicalActivity logact, out string endpointConfigName,
			Configuration configuration, CodeCompileUnit codeContracts)
		{
			MetadataSet mset = null;
			endpointConfigName = null;

			if ( currentSvcGenType == ServiceGenerationType.HumanActivityService ) {
				#region generate human activity client

				typeRefLogActContract = GenerateHumanActivityContract(codeContracts, typeProvider, logact, out contractnspace);

				endpointConfigName = logact.Name + "Url";
				configuration.AppSettings.Settings.Add(endpointConfigName, websvc.Uri);

				#endregion
				return;
			}

			using ( StringReader sr = new StringReader(websvc.MetaData) )
			using ( XmlReader xr = XmlReader.Create(sr) ) {
				mset = MetadataSet.ReadFrom(xr);
			}
			WsdlImporter wsdlimporter = new WsdlImporter(mset);
			if ( wsdlimporter.WsdlDocuments.Count > 0 ) {
				wsdl = wsdlimporter.WsdlDocuments[0];
				bindings = wsdlimporter.ImportAllBindings();
			}
			if ( wsdl != null ) {
				if ( string.IsNullOrEmpty(wsdl.Name) ) {
					if ( wsdl.Services.Count > 0 )
						contractnspace = wsdl.Services[0].Name + "Contract";
				} else {
					contractnspace = wsdl.Name + "Contract";
				}
				if ( currentSvcGenType == ServiceGenerationType.SystemWebService ) {
					#region generate asmx-webservice client
					Type t = null;
					if ( typeProvider != null ) {
						typeProvider.GetType(contractnspace + "." + websvc.Name);
					}
					if ( t != null ) {
						typeRefLogActContract = new CodeTypeReference(t);
					} else {
						// add url to app.config
						string appSettingsUrlKey = contractnspace + "." + websvc.Name + ".URL";
						if ( configuration != null ) {
							configuration.AppSettings.Settings.Add(appSettingsUrlKey, websvc.Uri);
							configuration.Save(ConfigurationSaveMode.Minimal);
						}
						// Initialize a service description importer.
						ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
						importer.ProtocolName = "Soap12";  // Use SOAP 1.2.
						importer.AddServiceDescription(wsdl, appSettingsUrlKey, websvc.Uri);

						// Generate a proxy client.
						importer.Style = ServiceDescriptionImportStyle.Client;

						// Generate properties to represent primitive values.
						importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties |
														 CodeGenerationOptions.GenerateNewAsync;

						// Initialize a Code-DOM tree into which we will import the service.
						CodeNamespace nmspace = new CodeNamespace(contractnspace);
						codeContracts.Namespaces.Add(nmspace);

						// Import the service into the Code-DOM tree. This creates proxy code
						// that uses the service.
						ServiceDescriptionImportWarnings warning = importer.Import(nmspace, codeContracts);
						// refresh typeProvider
						if ( typeProvider != null ) {
							RefreshTypeProvider(ref typeProvider, ref codeContracts);
							typeRefLogActContract = new CodeTypeReference(typeProvider.GetType(nmspace.Name + "." + websvc.Name));
						}
					}
					#endregion
				} else {
					#region generate wcf-webservice client
					Type t = null;
					if ( typeProvider != null ) {
						if ( string.IsNullOrEmpty(websvc.ClientFullName) ) {
							t = typeProvider.GetType(contractnspace + "." + websvc.Name + "Client");
						} else {
							t = typeProvider.GetType(websvc.ClientFullName);
						}
					}
					if ( t != null ) {
						if ( string.IsNullOrEmpty(websvc.InterfaceFullName) ) {
							typeRefLogActContract = new CodeTypeReference(
								typeProvider.GetType(contractnspace + ".I" + websvc.Name));
						} else {
							typeRefLogActContract = new CodeTypeReference(
								typeProvider.GetType(websvc.InterfaceFullName));
						}
					} else {
						CodeCompileUnit ccuNew = new CodeCompileUnit();
						ServiceContractGenerator generator;
						if ( configuration != null ) {
							generator = new ServiceContractGenerator(ccuNew, configuration);
						} else {
							generator = new ServiceContractGenerator(ccuNew);
						}
						generator.Options = ServiceContractGenerationOptions.ClientClass |
											ServiceContractGenerationOptions.AsynchronousMethods |
											ServiceContractGenerationOptions.EventBasedAsynchronousMethods;
						generator.NamespaceMappings.Add(wsdl.TargetNamespace, contractnspace);
						generator.NamespaceMappings.Add("*", contractnspace);
						generator.NamespaceMappings.Add("", contractnspace);
						ContractDescription cdesc = wsdlimporter.ImportContract(wsdl.PortTypes[0]);
						typeRefLogActContract = generator.GenerateServiceContractType(cdesc);

						foreach ( CodeNamespace codeNewNS in ccuNew.Namespaces ) {
							bool bNewNamespaceExists = false;
							foreach ( CodeNamespace codeNS in codeContracts.Namespaces ) {
								if ( codeNS.Name == codeNewNS.Name ) {
									bNewNamespaceExists = true;
									foreach ( CodeTypeDeclaration codeNewTypeDecl in codeNewNS.Types ) {
										bool bNewTypeExists = false;
										foreach ( CodeTypeDeclaration codeTypeDecl in codeNS.Types ) {
											if ( codeNewTypeDecl.Name == codeTypeDecl.Name ) {
												bNewTypeExists = true;
											}
										}
										if ( !bNewTypeExists ) {
											codeNS.Types.Add(codeNewTypeDecl);
										}
									}
								}
							}
							if ( !bNewNamespaceExists ) {
								codeContracts.Namespaces.Add(codeNewNS);
							}
						}
						foreach ( CodeAttributeDeclaration item in ccuNew.AssemblyCustomAttributes ) {
							codeContracts.AssemblyCustomAttributes.Add(item);
						}
						// generate endpoint config
						System.ServiceModel.Configuration.ChannelEndpointElement endpointElement = null;
						if ( configuration != null ) {
							generator.GenerateServiceEndpoint(
								new ServiceEndpoint(cdesc, bindings[0], new EndpointAddress(websvc.Uri)),
								out endpointElement);
							generator.Configuration.Save(ConfigurationSaveMode.Minimal, true);
						}
						if ( endpointElement != null ) {
							endpointConfigName = endpointElement.Name;
						}
						if ( typeProvider != null ) {
							// refresh typeProvider
							RefreshTypeProvider(ref typeProvider, ref codeContracts);
						}
					}
					#endregion
				}
			}
		}

		/// <summary>
		/// Gets the client type by contact type ref.
		/// </summary>
		/// <param name="codeContracts">The code contracts.</param>
		/// <param name="typeRefLogActContract">The type ref log act contract.</param>
		/// <param name="typeProvider">The type provider.</param>
		/// <returns></returns>
		internal Type GetClientTypeByContactTypeRef(CodeCompileUnit codeContracts, CodeTypeReference typeRefLogActContract,
			TypeProvider typeProvider)
		{
			string[] typename = typeRefLogActContract.BaseType.Split('.');
			Type typeClient = typeProvider.GetType(typeRefLogActContract.BaseType);
			if ( typeClient == null ) {
				foreach ( CodeNamespace codeNs in codeContracts.Namespaces ) {
					if ( codeNs.Name != typename[0] )
						continue;
					foreach ( CodeTypeDeclaration typeDecl in codeNs.Types ) {
						if ( typeDecl.IsClass && typeDecl.Name.EndsWith("Client") ) {
							typeClient = typeProvider.GetType(string.Format("{0}.{1}", codeNs.Name, typeDecl.Name));
							break;
						}
					}
				}
			}
			return typeClient;
		}

		#endregion

		#region Business Rules
		/// <summary>
		/// Adds the rule to  a code compile unit.
		/// </summary>
		/// <param name="businessRule">The business rule.</param>
		/// <param name="rulesCodeCompileUnit">The rules code compile unit.</param>
		/// <param name="workflow">The workflow.</param>
		/// <param name="listOfExistingRuleIds">The list of existing rule ids.</param>
		/// <param name="listOfRuleConstantIds">The list of rule constant ids.</param>
		internal void AddRuleToCodeCompileUnit(
			RepositoryBusinessRule businessRule,
			CodeCompileUnit rulesCodeCompileUnit,
			Repository.Workflow workflow,
			List<int> listOfExistingRuleIds,
			List<int> listOfRuleConstantIds)
		{
			#region check arguments
			Debug.Assert(businessRule != null);
			Debug.Assert(rulesCodeCompileUnit != null);
			Debug.Assert(workflow != null);
			Debug.Assert(listOfExistingRuleIds != null);
			Debug.Assert(listOfRuleConstantIds != null);
			#endregion

			RepositoryService repSvc = (RepositoryService)_serviceProvider.GetService(typeof(RepositoryService));
			List<int> usedrules = businessRule.GetUsedBusinessRuleIDs();
			List<int> usedconsts = businessRule.GetUsedRuleConstantIDs();
			if ( usedrules != null ) {
				foreach ( int ruleid in usedrules ) {
					if ( !listOfExistingRuleIds.Contains(ruleid) ) {
						Repository.RepositoryBusinessRule rule =
							repSvc.GetItem<OpenComposite.EII.Repository.RepositoryBusinessRule>(ruleid);
						AddRuleToCodeCompileUnit(rule, rulesCodeCompileUnit, workflow,
							listOfExistingRuleIds, listOfRuleConstantIds);
						listOfExistingRuleIds.Add(ruleid);
					}
				}
			}
			if ( usedconsts != null ) {
				foreach ( int constid in usedconsts ) {
					if ( !listOfRuleConstantIds.Contains(constid) ) listOfRuleConstantIds.Add(constid);
				}
			}
			if ( rulesCodeCompileUnit != null && rulesCodeCompileUnit.Namespaces.Count > 0 &&
				 rulesCodeCompileUnit.Namespaces[0].Types.Count > 0 ) {
				// search for existing rules
				foreach ( CodeTypeMember codeMember in rulesCodeCompileUnit.Namespaces[0].Types[0].Members ) {
					CodeMemberMethod m = codeMember as CodeMemberMethod;
					if ( m != null && m.Name == businessRule.Name ) {
						// if method exists for this rule: exit
						return;
					}
				}
				// create and add rule method
				CodeMemberMethod codeMeth = new CodeMemberMethod();
				codeMeth.Name = businessRule.Name;
				if ( workflow.IsConfigurable ) {
					codeMeth.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				} else {
					codeMeth.Attributes = MemberAttributes.Public | MemberAttributes.Static | MemberAttributes.Final;
				}
				codeMeth.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(RepositoryInformationAttribute)),
						new CodeAttributeArgument(new CodePrimitiveExpression(businessRule.ID)),
						new CodeAttributeArgument(new CodePrimitiveExpression(businessRule.Name)),
						new CodeAttributeArgument(
							new CodePrimitiveExpression(businessRule.RepositoryItemTypeName)),
						new CodeAttributeArgument(
							new CodePrimitiveExpression(
								Helper.GetMD5HashAsHex(businessRule.RuleCode)))));
				codeMeth.ReturnType = new CodeTypeReference(typeof(string));
				foreach ( KeyValuePair<string, string> name_type in businessRule.GetParameters() ) {
					Type typeParam = OpenComposite.EII.Helpers.GetDotNetTypeOfDataTypeString(name_type.Value);
					CodeTypeReference typeRefParam = null;
					if ( typeParam.IsValueType ) {
						typeRefParam = new CodeTypeReference();
						typeRefParam.BaseType = "System.Nullable";
						typeRefParam.TypeArguments.Add(typeParam);
					} else {
						typeRefParam = new CodeTypeReference(typeParam);
					}
					codeMeth.Parameters.Add(
						new CodeParameterDeclarationExpression(
							typeRefParam,
							name_type.Key));
				}
				string code = businessRule.RuleCode;
				code = code.Substring(code.IndexOf("{") + 1, code.LastIndexOf("}") - code.IndexOf("{") - 1);
				code = code.Replace(Environment.NewLine, Environment.NewLine + "\t\t");
				codeMeth.Statements.Add(new CodeSnippetStatement(code));
				rulesCodeCompileUnit.Namespaces[0].Types[0].Members.Add(codeMeth);

				TypeProvider typeProvider = (TypeProvider)_serviceProvider.GetService(typeof(ITypeProvider));
				if ( typeProvider != null ) RefreshTypeProvider(ref typeProvider, ref rulesCodeCompileUnit);

				if ( !listOfExistingRuleIds.Contains(businessRule.ID) ) {
					listOfExistingRuleIds.Add(businessRule.ID);
				}
			}
		}

		/// <summary>
		/// Gets the business rule invoke expression.
		/// </summary>
		/// <param name="orchestrationTargetObject">The orchestration target object.</param>
		/// <param name="brule">The brule.</param>
		/// <param name="namespaceRules">The namespace rules.</param>
		/// <returns></returns>
		internal CodeMethodInvokeExpression GetBusinessRuleInvokeExpression(
			CodeCompileUnit ccuRules,
			CodeExpression orchestrationTargetObject, Repository.RepositoryBusinessRule brule,
			string namespaceRules)
		{
			List<CodeExpression> lstRuleParams = new List<CodeExpression>();
			Dictionary<string, string> ruleparameters = brule.GetParameters();
			if ( ruleparameters != null ) {
				foreach ( string paramName in ruleparameters.Keys ) {
					lstRuleParams.Add(
						new CodePropertyReferenceExpression(
							orchestrationTargetObject,
							paramName));
				}
			}
			string rulesclass = namespaceRules + ".Rules";
			CodeMemberMethod methRule = Helpers.GetMember<CodeMemberMethod>(
				ccuRules, rulesclass, brule.Name);

			CodeExpression ruleTargetObj =
				( methRule.Attributes & MemberAttributes.Static ) == MemberAttributes.Static ?
				(CodeExpression)new CodeTypeReferenceExpression(rulesclass) :
				(CodeExpression)new CodePropertyReferenceExpression(
					orchestrationTargetObject,
					"Rules");
			CodeMethodInvokeExpression methinvoke = new CodeMethodInvokeExpression(
				ruleTargetObj,
				brule.Name,
				lstRuleParams.ToArray());
			return methinvoke;
		}

		internal void GenerateRuleConstantsCode(CodeTypeDeclaration ctdRules,
			Repository.Workflow workflow, Configuration configuration,
			ICollection<RuleConstant> ruleconstants)
		{
			CodeConstructor ctorRules = null;
			if ( workflow.IsConfigurable ) {
				ctorRules = new CodeConstructor();
				ctorRules.Attributes = MemberAttributes.Public;
				ctdRules.Members.Add(ctorRules);
			}
			foreach ( var rc in ruleconstants ) {
				if ( rc != null ) {
					CodeMemberField fieldConst = new CodeMemberField();
					fieldConst.Name = CodeGen.ConstPrefix + rc.Name;
					fieldConst.Type = new CodeTypeReference(Global.Data.GetDOTNETTypeofXSDDataType(rc.DataType));
					if ( workflow.IsConfigurable ) {
						fieldConst.Attributes = MemberAttributes.Private;
						if ( ctorRules != null ) {
							// add intialization to ctor
							//try {
							//    this.CONST_HighBudgetScore = Convert.ChangeType(
							//        System.Configuration.ConfigurationManager.AppSettings["CONST_HighBudgetScore"],
							//        typeof(decimal));
							//} catch { }
							CodeTryCatchFinallyStatement codeTry = new CodeTryCatchFinallyStatement();
							codeTry.TryStatements.Add(
								new CodeAssignStatement(
									new CodeFieldReferenceExpression(null, fieldConst.Name),
									new CodeCastExpression(
										Global.Data.GetDOTNETTypeofXSDDataType(rc.DataType),
										new CodeMethodInvokeExpression(
											new CodeTypeReferenceExpression(typeof(Convert)),
											"ChangeType",
											new CodeArrayIndexerExpression(
												new CodePropertyReferenceExpression(
													new CodeTypeReferenceExpression(typeof(ConfigurationManager)),
													"AppSettings"),
												new CodePrimitiveExpression(fieldConst.Name)),
											new CodeTypeOfExpression(
												Global.Data.GetDOTNETTypeofXSDDataType(rc.DataType))))));
							codeTry.CatchClauses.Add(new CodeCatchClause());
							ctorRules.Statements.Add(codeTry);
							if ( configuration != null ) {
								configuration.AppSettings.Settings.Add(fieldConst.Name, rc.Value);
							}
						}
					} else {
						fieldConst.Attributes = MemberAttributes.Private | MemberAttributes.Const;
					}

					object val = rc.GetValueObject();
					if ( val != null ) {
						fieldConst.InitExpression = new CodePrimitiveExpression(val);
					} else {
						fieldConst.InitExpression = new CodeDefaultValueExpression(fieldConst.Type);
					}
					ctdRules.Members.Add(fieldConst);
				}
			}
		}

		#endregion

		#region Human Activity
		/// <summary>
		/// Generates the human activity contract.
		/// </summary>
		/// <param name="codeContracts">The contracts code compile unit.</param>
		/// <param name="typeProvider">The type provider.</param>
		/// <param name="logact">The logical activity.</param>
		/// <param name="contractnspace">The contract namespace.</param>
		/// <returns>The <see cref="T:System.CodeDom.CodeTypeReference"/> of the human activity contract.</returns>
		internal CodeTypeReference GenerateHumanActivityContract(
			CodeCompileUnit codeContracts, TypeProvider typeProvider,
			Repository.LogicalActivity logact, out string contractnspace)
		{
			contractnspace = "";
			Repository.HumanActivity ha = logact.LogicalMethod.GetAssignedHumanActivity();
			if ( ha == null ) return null;

			#region constants
			const string cNamespace = "Namespace";
			const string cHANamespace = "http://www.OpenComposite.com/HumanActivity";
			const string cIsOneWay = "IsOneWay";
			const string cIHumanActivityService = "IHumanActivityService";
			const string cIHumanActivityServiceCallback = "IHumanActivityServiceCallback";
			const string cInstanceContextMode = "InstanceContextMode";
			const string cfindFreePort = "findFreePort";
			const string cHumanActivityStart = "HumanActivityStart";
			const string cHumanActivityCompleted = "HumanActivityCompleted";
			const string cHumanActivityFaulted = "HumanActivityFaulted";
			const string cHumanActivityAborted = "HumanActivityAborted";
			const string cFormSchemaWrapper = "FormSchemaWrapper";

			const string c_result = "_result";
			const string c_callbackUri = "_callbackUri";
			const string c_msgId = "_msgId";
			const string c_host = "_host";
			const string c_waitHandle = "_waitHandle";

			#endregion

			string logactName = logact.Name;
			string formschemaTypeName = ha.FormSchemaName;
			if ( formschemaTypeName.Contains(".") ) {
				string[] splits = formschemaTypeName.Split('.');
				formschemaTypeName = splits[splits.Length - 1];
			}

			// namespace SERVICENAMEContract
			contractnspace = ha.Name/*logactName*/ + "Contract";
			string clientname = ha.Name/*logactName*/ + "Client";
			Type t = null;
			if ( typeProvider != null ) typeProvider.GetType(contractnspace + "." + clientname);
			if ( t != null ) {
				return new CodeTypeReference(t);
			} else {
				CodeNamespace codeNSHAClient = null;
				bool containsNamespace = false;
				foreach ( CodeNamespace ns in codeContracts.Namespaces ) {
					if ( ns.Name == contractnspace ) {
						containsNamespace = true;
						codeNSHAClient = ns;
						foreach ( CodeTypeDeclaration ctd in ns.Types ) {
							if ( ctd.Name == clientname ) {
								return new CodeTypeReference(contractnspace + "." + clientname);
							}
						}
					}
				}
				if ( !containsNamespace ) codeNSHAClient = new CodeNamespace(contractnspace);

				#region add imports
				codeNSHAClient.Imports.Add(new CodeNamespaceImport("System"));
				codeNSHAClient.Imports.Add(new CodeNamespaceImport("System.IO"));
				codeNSHAClient.Imports.Add(new CodeNamespaceImport("System.Threading"));
				codeNSHAClient.Imports.Add(new CodeNamespaceImport("System.Xml"));
				codeNSHAClient.Imports.Add(new CodeNamespaceImport("System.Xml.Serialization"));
				codeNSHAClient.Imports.Add(new CodeNamespaceImport("System.ServiceModel"));
				codeNSHAClient.Imports.Add(new CodeNamespaceImport("OpenComposite.HumanActivity.Contracts"));
				codeNSHAClient.Imports.Add(new CodeNamespaceImport("OpenComposite.HumanActivity.Contracts.Participants"));
				#endregion

				#region add formschema
				AddSchemaClassesToCodeNamespace(codeNSHAClient, ha.FormSchema);
				#endregion

				#region add FormSchemaWrapper
				if ( ha.FormSchema == null )
					throw new NullReferenceException("Missing form schema at human activity form \"" + ha.Name + "\".");
				if ( string.IsNullOrEmpty(formschemaTypeName) )
					throw new NullReferenceException("Missing form schema name at human activity form \"" + ha.Name + "\".");
				CodeTypeDeclaration codeFSWrap = new CodeTypeDeclaration();
				codeFSWrap.Attributes = MemberAttributes.Public;
				codeFSWrap.Name = cFormSchemaWrapper;
				codeFSWrap.CustomAttributes.Add(	// [SerializableAttribute]
					new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));

				codeFSWrap.CustomAttributes.Add(	// [System.Xml.Serialization.XmlTypeAttribute(
					new CodeAttributeDeclaration(	//	AnonymousType=true, Namespace="http://www.OpenComposite.com/HumanActivity")]
						new CodeTypeReference(typeof(XmlTypeAttribute)),
						new CodeAttributeArgument("AnonymousType", new CodePrimitiveExpression(true)),
						new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(ha.FormSchema.TargetNamespace))));
				CodeConstructor ctorFSWrapNoParams = new CodeConstructor();
				ctorFSWrapNoParams.Attributes = MemberAttributes.Public;
				codeFSWrap.Members.Add(ctorFSWrapNoParams);

				CodeConstructor ctorFSWrap = new CodeConstructor();
				ctorFSWrap.Attributes = MemberAttributes.Public;
				ctorFSWrap.Parameters.Add(new CodeParameterDeclarationExpression(formschemaTypeName, "data"));
				ctorFSWrap.Statements.Add(
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), formschemaTypeName),
						new CodeArgumentReferenceExpression("data")));
				codeFSWrap.Members.Add(ctorFSWrap);
				CodeMemberField fieldFS = new CodeMemberField(formschemaTypeName, formschemaTypeName);
				fieldFS.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				codeFSWrap.Members.Add(fieldFS);

				codeNSHAClient.Types.Add(codeFSWrap);
				#endregion

				#region add IHumanActivityService interface
				CodeTypeDeclaration codeIHAService = new CodeTypeDeclaration(cIHumanActivityService);
				codeIHAService.Attributes = MemberAttributes.Public;
				codeIHAService.IsInterface = true;
				codeIHAService.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(ServiceContractAttribute)),
						new CodeAttributeArgument(cNamespace, new CodePrimitiveExpression(cHANamespace))));
				// add method HumanActivityStart to  interface
				CodeMemberMethod methHAStart = new CodeMemberMethod();
				methHAStart.Name = cHumanActivityStart;
				methHAStart.Attributes = (MemberAttributes)0;
				methHAStart.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(OperationContractAttribute))));//,
				//new CodeAttributeArgument(cIsOneWay, new CodePrimitiveExpression(true))));
				methHAStart.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(XmlSerializerFormatAttribute))));
				methHAStart.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(FaultContractAttribute)),
						new CodeAttributeArgument(
							new CodeTypeOfExpression(typeof(HumanActivityFault)))));
				methHAStart.Parameters.Add(
					new CodeParameterDeclarationExpression(cFormSchemaWrapper, "data"));
				codeIHAService.Members.Add(methHAStart);

				codeNSHAClient.Types.Add(codeIHAService);
				#endregion

				#region add IHumanActivityServiceCallback interface
				//Completed
				CodeTypeDeclaration codeIHASCallback = new CodeTypeDeclaration(cIHumanActivityServiceCallback);
				codeIHASCallback.Attributes = MemberAttributes.Public;
				codeIHASCallback.IsInterface = true;
				codeIHASCallback.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(ServiceContractAttribute)),
						new CodeAttributeArgument(cNamespace, new CodePrimitiveExpression(cHANamespace))));
				// add method HumanActivityCompleted to interface
				CodeMemberMethod methHAComplete = new CodeMemberMethod();
				methHAComplete.Name = cHumanActivityCompleted;
				methHAComplete.Attributes = (MemberAttributes)0;
				methHAComplete.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(OperationContractAttribute)),
						new CodeAttributeArgument(cIsOneWay, new CodePrimitiveExpression(true))));
				methHAComplete.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(XmlSerializerFormatAttribute))));
				methHAComplete.Parameters.Add(
					new CodeParameterDeclarationExpression(cFormSchemaWrapper, "data"));
				codeIHASCallback.Members.Add(methHAComplete);

				// add method HumanActivityFaulted to interface
				CodeMemberMethod methHAFault = new CodeMemberMethod();
				methHAFault.Name = cHumanActivityFaulted;
				methHAFault.Attributes = (MemberAttributes)0;
				methHAFault.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(OperationContractAttribute)),
						new CodeAttributeArgument(cIsOneWay, new CodePrimitiveExpression(true))));
				methHAFault.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(XmlSerializerFormatAttribute))));
				methHAFault.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(HumanActivityFault), "fault"));
				codeIHASCallback.Members.Add(methHAFault);

				// add method HumanActivityAborted to interface
				CodeMemberMethod methHAAbort = new CodeMemberMethod();
				methHAAbort.Name = cHumanActivityAborted;
				methHAAbort.Attributes = (MemberAttributes)0;
				methHAAbort.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(OperationContractAttribute)),
						new CodeAttributeArgument(cIsOneWay, new CodePrimitiveExpression(true))));
				methHAAbort.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(XmlSerializerFormatAttribute))));
				methHAAbort.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(HumanActivityFault), "fault"));
				codeIHASCallback.Members.Add(methHAAbort);

				codeNSHAClient.Types.Add(codeIHASCallback);
				#endregion

				#region add client class
				CodeTypeDeclaration codeClient = new CodeTypeDeclaration(clientname);
				codeClient.Attributes = MemberAttributes.Public;
				codeClient.BaseTypes.Add(cIHumanActivityServiceCallback);
				codeClient.CustomAttributes.Add(
					new CodeAttributeDeclaration(
						new CodeTypeReference(typeof(ServiceBehaviorAttribute)),
						new CodeAttributeArgument(
							cInstanceContextMode,
							new CodeFieldReferenceExpression(
								new CodeTypeReferenceExpression(typeof(InstanceContextMode)), "Single"))));

				// add private fields
				codeClient.Members.AddRange(new CodeMemberField[] {
					new CodeMemberField(formschemaTypeName, c_result),
					new CodeMemberField(typeof(Uri), c_callbackUri),
					new CodeMemberField(typeof(UniqueId), c_msgId),
					new CodeMemberField(typeof(ServiceHost), c_host),
					new CodeMemberField(typeof(AutoResetEvent), c_waitHandle),
					new CodeMemberField(typeof(Exception), "_fault")
				});

				#region add constructor
				CodeConstructor codeCtor = new CodeConstructor();
				codeCtor.Attributes = MemberAttributes.Public;
				codeCtor.Statements.Add(
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_waitHandle),
						new CodeObjectCreateExpression(typeof(AutoResetEvent), new CodePrimitiveExpression(false))));
				codeCtor.Statements.Add(
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_callbackUri),
						new CodeObjectCreateExpression(
							typeof(Uri),
							new CodeMethodInvokeExpression(
								new CodeTypeReferenceExpression(typeof(string)),
								"Format",
								new CodePrimitiveExpression("net.tcp://{0}:{1}/HumanCallback"),
								new CodePropertyReferenceExpression(
									new CodeTypeReferenceExpression(typeof(Environment)), "MachineName"),
								new CodeMethodInvokeExpression(
									new CodeThisReferenceExpression(), cfindFreePort)))));
				codeCtor.Statements.Add(
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_msgId),
						new CodeObjectCreateExpression(typeof(UniqueId))));

				codeCtor.Statements.Add(
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_host),
						new CodeObjectCreateExpression(typeof(ServiceHost), new CodeThisReferenceExpression())));
				codeCtor.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_host),
						"AddServiceEndpoint",
						new CodeTypeOfExpression(cIHumanActivityServiceCallback),
						new CodeObjectCreateExpression(typeof(NetTcpBinding)),
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_callbackUri)));
				codeCtor.Statements.Add(
					new CodeMethodInvokeExpression(
					new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_host),
					"Open"));
				codeClient.Members.Add(codeCtor);
				#endregion

				#region add public DoHumanActivity method
				//const string includedParticipants = "includedParticipants";
				//const string excludedParticipants = "excludedParticipants";
				//const string userIds = "userIds";
				//const string roleIds = "roleIds";
				//const string orgUnitIds = "orgUnitIds";

				CodeTypeReference typeRefListOfParticipantItems = new CodeTypeReference(typeof(List<>));
				typeRefListOfParticipantItems.TypeArguments.Add(typeof(ParticipantItem));

				CodeMemberMethod methDoHA = new CodeMemberMethod();
				methDoHA.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				methDoHA.Name = "DoHumanActivity";
				methDoHA.Parameters.AddRange(new CodeParameterDeclarationExpression[]{
					new CodeParameterDeclarationExpression(typeof(Guid), "workflowInstanceId"),
					new CodeParameterDeclarationExpression(typeof(string), "activityName"),
					new CodeParameterDeclarationExpression(typeof(string), "processName"),
					new CodeParameterDeclarationExpression(typeof(string), "subject"),
					new CodeParameterDeclarationExpression(typeof(string), "targetURLKey"),
					new CodeParameterDeclarationExpression(formschemaTypeName, "input"),
					new CodeParameterDeclarationExpression(typeRefListOfParticipantItems, "participants")
				});
				methDoHA.ReturnType = new CodeTypeReference(formschemaTypeName);

				// string url = ConfigurationManager.AppSettings[targetURLKey];
				methDoHA.Statements.Add(
					new CodeVariableDeclarationStatement(
						typeof(string),
						"url",
						new CodeArrayIndexerExpression(
							new CodePropertyReferenceExpression(
								new CodeTypeReferenceExpression(typeof(ConfigurationManager)),
								cAppSettings),
							new CodeArgumentReferenceExpression("targetURLKey"))));

				//OpenComposite.HumanActivity.Contracts.ActivityItem ai =
				//    ActivityItemFactory.Create(workflowInstanceId, activityName, processName, subject, url);
				methDoHA.Statements.Add(new CodeCommentStatement("Initialize ActivityItem with informations required by the Human Activity Service."));
				methDoHA.Statements.Add(
					new CodeVariableDeclarationStatement(
						typeof(ActivityItem),
						"ai",
						new CodeMethodInvokeExpression(
							new CodeTypeReferenceExpression(typeof(ActivityItemFactory)),
							"Create",
							new CodeArgumentReferenceExpression("workflowInstanceId"),
							new CodeArgumentReferenceExpression("activityName"),
							new CodeArgumentReferenceExpression("processName"),
							new CodeArgumentReferenceExpression("subject"),
							new CodeVariableReferenceExpression("url"))));
				methDoHA.Statements.Add(new CodeCommentStatement("Add Human Activity Participants."));
				////foreach component participant:
				////ai.AddParticipant(participantType, participantId, participationType);
				//foreach ( var part in logact.ExtendedProperties.HumanComponentProperties.Participants ) {
				//    methDoHA.Statements.Add(
				//        new CodeMethodInvokeExpression(
				//            new CodeVariableReferenceExpression("ai"),
				//            "AddParticipant",
				//            new CodePropertyReferenceExpression(
				//                new CodeTypeReferenceExpression(typeof(ParticipantType)),
				//                part.Type.ToString()),
				//            new CodePrimitiveExpression(part.ID),
				//            new CodePropertyReferenceExpression(
				//                new CodeTypeReferenceExpression(typeof(ParticipationType)),
				//                part.ParticipationType.ToString())));
				//}
				//if ( participants != null) {
				//	ai.Participants.AddRange(participants);
				//}
				CodeConditionStatement ifPartsNull =
					new CodeConditionStatement(
						new CodeBinaryOperatorExpression(
							new CodeVariableReferenceExpression("participants"),
							CodeBinaryOperatorType.IdentityInequality,
							new CodePrimitiveExpression(null)));
				ifPartsNull.TrueStatements.Add(
						new CodeMethodInvokeExpression(
							new CodePropertyReferenceExpression(
								new CodeVariableReferenceExpression("ai"), "Participants"),
							"AddRange",
							new CodeArgumentReferenceExpression("participants")));
				methDoHA.Statements.Add(ifPartsNull);

				#region generate parse included/excluded users, roles and ourgunits
				//methDoHA.Statements.Add(
				//    new CodeVariableDeclarationStatement(typeof(string), userIds));
				//methDoHA.Statements.Add(
				//    new CodeVariableDeclarationStatement(typeof(string), roleIds));
				//methDoHA.Statements.Add(
				//    new CodeVariableDeclarationStatement(typeof(string), orgUnitIds));
				//methDoHA.Statements.Add(new CodeCommentStatement("parse included users, roles and ourgunits"));
				//methDoHA.Statements.Add(
				//    new CodeMethodInvokeExpression(
				//        new CodeThisReferenceExpression(), "splitParticipants",
				//        new CodeVariableReferenceExpression(includedParticipants),
				//        new CodeDirectionExpression(
				//            FieldDirection.Out, new CodeVariableReferenceExpression(userIds)),
				//        new CodeDirectionExpression(
				//            FieldDirection.Out, new CodeVariableReferenceExpression(roleIds)),
				//        new CodeDirectionExpression(
				//            FieldDirection.Out, new CodeVariableReferenceExpression(orgUnitIds))));
				////new CodeSnippetExpression("out " + userIds),
				////new CodeSnippetExpression("out " + roleIds),
				////new CodeSnippetExpression("out " + orgUnitIds)));
				//methDoHA.Statements.Add(
				//    new CodeAssignStatement(
				//        new CodeFieldReferenceExpression(
				//            new CodeVariableReferenceExpression("ai"), "AdhocInclUsers"),
				//        new CodeVariableReferenceExpression(userIds)));
				//methDoHA.Statements.Add(
				//    new CodeAssignStatement(
				//        new CodeFieldReferenceExpression(
				//            new CodeVariableReferenceExpression("ai"), "AdhocInclRoles"),
				//        new CodeVariableReferenceExpression(roleIds)));
				//methDoHA.Statements.Add(
				//    new CodeAssignStatement(
				//        new CodeFieldReferenceExpression(
				//            new CodeVariableReferenceExpression("ai"), "AdhocInclOrgs"),
				//        new CodeVariableReferenceExpression(orgUnitIds)));
				//methDoHA.Statements.Add(new CodeCommentStatement("parse excluded users, roles and ourgunits"));
				//methDoHA.Statements.Add(
				//    new CodeMethodInvokeExpression(
				//        new CodeThisReferenceExpression(), "splitParticipants",
				//        new CodeVariableReferenceExpression(excludedParticipants),
				//        new CodeSnippetExpression("out " + userIds),
				//        new CodeSnippetExpression("out " + roleIds),
				//        new CodeSnippetExpression("out " + orgUnitIds)));
				//methDoHA.Statements.Add(
				//    new CodeAssignStatement(
				//        new CodeFieldReferenceExpression(
				//            new CodeVariableReferenceExpression("ai"), "AdhocExclUsers"),
				//        new CodeVariableReferenceExpression(userIds)));
				//methDoHA.Statements.Add(
				//    new CodeAssignStatement(
				//        new CodeFieldReferenceExpression(
				//            new CodeVariableReferenceExpression("ai"), "AdhocExclRoles"),
				//        new CodeVariableReferenceExpression(roleIds)));
				//methDoHA.Statements.Add(
				//    new CodeAssignStatement(
				//        new CodeFieldReferenceExpression(
				//            new CodeVariableReferenceExpression("ai"), "AdhocExclOrgs"),
				//        new CodeVariableReferenceExpression(orgUnitIds)));
				#endregion
				//EndpointAddress targetEP = new EndpointAddress(url);
				methDoHA.Statements.Add(
					new CodeVariableDeclarationStatement(typeof(EndpointAddress), "targetEP",
						new CodeObjectCreateExpression(
							typeof(EndpointAddress),
							new CodeVariableReferenceExpression("url"))));
				//new CodeArgumentReferenceExpression("targetURL"))));
				CodeTypeReference typeRefHAChannel = new CodeTypeReference(typeof(ChannelFactory<>));
				typeRefHAChannel.TypeArguments.Add(cIHumanActivityService);
				methDoHA.Statements.Add(
					new CodeVariableDeclarationStatement(typeRefHAChannel, "factory",
						new CodeObjectCreateExpression(typeRefHAChannel,
							new CodeObjectCreateExpression(typeof(NetTcpBinding)),
							new CodeVariableReferenceExpression("targetEP"))));
				methDoHA.Statements.Add(
					new CodeVariableDeclarationStatement(cIHumanActivityService, "channel",
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("factory"),
							"CreateChannel")));
				methDoHA.Statements.Add(
					new CodeVariableDeclarationStatement(typeof(OperationContextScope), "scope",
						new CodeObjectCreateExpression(
							typeof(OperationContextScope),
							new CodeCastExpression(
								typeof(IContextChannel), new CodeVariableReferenceExpression("channel")))));

				CodeTryCatchFinallyStatement tryfinalScope = new CodeTryCatchFinallyStatement();
				tryfinalScope.TryStatements.Add(
					new CodeAssignStatement(
						new CodePropertyReferenceExpression(
							new CodePropertyReferenceExpression(
								new CodePropertyReferenceExpression(
									new CodeTypeReferenceExpression(typeof(OperationContext)),
									"Current"),
								"OutgoingMessageHeaders"),
							"ReplyTo"),
						new CodeObjectCreateExpression(
							typeof(EndpointAddress),
							new CodeFieldReferenceExpression(
								new CodeThisReferenceExpression(), c_callbackUri))));
				tryfinalScope.TryStatements.Add(
					new CodeAssignStatement(
						new CodePropertyReferenceExpression(
							new CodePropertyReferenceExpression(
								new CodePropertyReferenceExpression(
									new CodeTypeReferenceExpression(typeof(OperationContext)),
									"Current"),
								"OutgoingMessageHeaders"),
							"MessageId"),
						new CodeFieldReferenceExpression(
							new CodeThisReferenceExpression(), c_msgId)));
				tryfinalScope.TryStatements.Add(
					new CodeMethodInvokeExpression(
						new CodePropertyReferenceExpression(
							new CodePropertyReferenceExpression(
								new CodeTypeReferenceExpression(typeof(OperationContext)),
								"Current"),
							"OutgoingMessageHeaders"),
						"Add",
						new CodeMethodInvokeExpression(
							new CodeTypeReferenceExpression(typeof(MessageHeader)), "CreateHeader",
							new CodePrimitiveExpression("ActivityItem"),
							new CodePrimitiveExpression(cHANamespace),
							new CodeVariableReferenceExpression("ai"))));
				tryfinalScope.TryStatements.Add(
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("channel"), cHumanActivityStart,
						new CodeObjectCreateExpression(
							cFormSchemaWrapper,
							new CodeArgumentReferenceExpression("input"))));
				tryfinalScope.FinallyStatements.Add(
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("scope"), "Dispose"));
				methDoHA.Statements.Add(tryfinalScope);
				methDoHA.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("factory"), "Close"));
				methDoHA.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_waitHandle),
						"WaitOne"));
				methDoHA.Statements.Add(
					new CodeConditionStatement(
						new CodeBinaryOperatorExpression(
							new CodeFieldReferenceExpression(null, "_fault"),
							CodeBinaryOperatorType.IdentityInequality,
							new CodePrimitiveExpression(null)),
						new CodeStatement[]{
							new CodeThrowExceptionStatement(
								new CodeFieldReferenceExpression(null, "_fault"))
						},
						new CodeStatement[]{
							new CodeMethodReturnStatement(
								new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_result))
						}));

				//methDoHA.Statements.Add(			
				//    new CodeMethodReturnStatement(
				//        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_result)));

				codeClient.Members.Add(methDoHA);
				#endregion

				#region add private findFreePort method
				CreateFindFreePortMethod(cfindFreePort, codeClient);
				#endregion

				//#region add private splitParticipants method

				//codeClient.Members.Add(
				//    new CodeSnippetTypeMember(CodeSnippets.CodeMethod_splitParticipants));

				//#endregion

				#region add public HumanActivityCompleted method in #region IHumanActivityServiceCallback Members

				CodeMemberMethod methHACompleted = new CodeMemberMethod();
				methHACompleted.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				methHACompleted.Name = cHumanActivityCompleted;
				methHACompleted.Parameters.Add(
					new CodeParameterDeclarationExpression(cFormSchemaWrapper, "data"));
				// add method to region
				methHACompleted.StartDirectives.Add(
					new CodeRegionDirective(CodeRegionMode.Start, "IHumanActivityServiceCallback Members"));
				//methHACompleted.EndDirectives.Add(
				//    new CodeRegionDirective(CodeRegionMode.End, "IHumanActivityServiceCallback Members"));

				methHACompleted.Statements.Add(
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_result),
						new CodePropertyReferenceExpression(
							new CodeArgumentReferenceExpression("data"), formschemaTypeName)));
				methHACompleted.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_host), "Close"));
				methHACompleted.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_waitHandle), "Set"));

				codeClient.Members.Add(methHACompleted);

				#endregion

				#region add public HumanActivityFaulted method in #region IHumanActivityServiceCallback Members

				CodeMemberMethod methHAFaulted = new CodeMemberMethod();
				methHAFaulted.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				methHAFaulted.Name = cHumanActivityFaulted;
				methHAFaulted.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(HumanActivityFault), "fault"));
				// add method to region
				//methHAFaulted.StartDirectives.Add(
				//    new CodeRegionDirective(CodeRegionMode.Start, "IHumanActivityServiceCallback Members"));
				//methHAFaulted.EndDirectives.Add(
				//    new CodeRegionDirective(CodeRegionMode.End, "IHumanActivityServiceCallback Members"));

				//methHAFaulted.Statements.Add(
				//    new CodeAssignStatement(
				//        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_result),
				//        new CodePropertyReferenceExpression(
				//            new CodeArgumentReferenceExpression("data"), formschemaTypeName)));
				methHAFaulted.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_host), "Close"));
				methHAFaulted.Statements.Add(
					new CodeAssignStatement(
						new CodeFieldReferenceExpression(null, "_fault"),
						new CodeObjectCreateExpression(
							typeof(FaultException<HumanActivityFault>),
							new CodeArgumentReferenceExpression("fault"))));
				methHAFaulted.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_waitHandle), "Set"));


				codeClient.Members.Add(methHAFaulted);

				#endregion

				#region add public HumanActivityAbort method in #region IHumanActivityServiceCallback Members

				CodeMemberMethod methHAAborted = new CodeMemberMethod();
				methHAAborted.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				methHAAborted.Name = cHumanActivityAborted;
				methHAAborted.Parameters.Add(
					new CodeParameterDeclarationExpression(typeof(HumanActivityFault), "fault"));
				// add method to region
				//methHAAborted.StartDirectives.Add(
				//    new CodeRegionDirective(CodeRegionMode.Start, "IHumanActivityServiceCallback Members"));
				methHAAborted.EndDirectives.Add(
					new CodeRegionDirective(CodeRegionMode.End, "IHumanActivityServiceCallback Members"));

				//methHAAborted.Statements.Add(
				//    new CodeAssignStatement(
				//        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_result),
				//        new CodePropertyReferenceExpression(
				//            new CodeArgumentReferenceExpression("data"), formschemaTypeName)));
				methHAAborted.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_host), "Close"));
				methHAAborted.Statements.Add(
					new CodeMethodInvokeExpression(
						new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), c_waitHandle), "Set"));

				codeClient.Members.Add(methHAAborted);

				#endregion


				#region add public Abort method
				CodeMemberMethod methAbort = new CodeMemberMethod();
				methAbort.Attributes = MemberAttributes.Public | MemberAttributes.Final;
				methAbort.Name = "Abort";

				codeClient.Members.Add(methAbort);
				#endregion

				codeNSHAClient.Types.Add(codeClient);
				#endregion

				if ( !containsNamespace ) codeContracts.Namespaces.Add(codeNSHAClient);
				if ( typeProvider != null ) RefreshTypeProvider(ref typeProvider, ref codeContracts);

				return new CodeTypeReference(codeNSHAClient.Name + "." + codeClient.Name);
			}
		}
		#endregion

		#region Generate Mapping

		/// <summary>
		/// Generates the mapping.
		/// </summary>
		/// <param name="codeContracts">The code contracts.</param>
		/// <param name="codeMapping">The code mapping.</param>
		/// <param name="ctdMapping">The CTD mapping.</param>
		/// <param name="ctorMapping">The ctor mapping.</param>
		/// <param name="configuration">The configuration.</param>
		/// <param name="currentSvcGenType">Type of the current SVC gen.</param>
		/// <param name="typeProvider">The type provider.</param>
		/// <param name="typeRefLogActContract">The type ref log act contract.</param>
		/// <param name="logicalName">Name of the logical.</param>
		/// <param name="logact">The logact.</param>
		/// <param name="logwmeth">The logwmeth.</param>
		/// <param name="logresultep">The logresultep.</param>
		/// <param name="webmeth">The webmeth.</param>
		/// <param name="wmCallback">The wm callback.</param>
		/// <param name="methInMap">The meth in map.</param>
		/// <param name="methOutMap">The meth out map.</param>
		/// <param name="methContract">The meth contract.</param>
		/// <param name="typeRefMapClass">The type ref map class.</param>
		/// <param name="typeRefOutput">The type ref output.</param>
		/// <param name="typeRefInput">The type ref input.</param>
		/// <param name="listTypeRefInputLogAct">The list type ref input log act.</param>
		/// <param name="useProxy">if set to <c>true</c> [use proxy].</param>
		/// <param name="generateConfigLogPhys">if set to <c>true</c> [generate config log phys].</param>
		/// <param name="isDomainConfigLogPhys">if set to <c>true</c> [is domain config log phys].</param>
		/// <param name="generateConfigSubscribe">if set to <c>true</c> [generate config subscribe].</param>
		/// <param name="isDomainConfigSubscribe">if set to <c>true</c> [is domain config subscribe].</param>
		internal void GenerateMapping(
			CodeCompileUnit codeContracts,
			CodeCompileUnit codeMapping,
			CodeTypeDeclaration ctdMapping,
			CodeConstructor ctorMapping,
			Configuration configuration,
			ServiceGenerationType currentSvcGenType,
			ref TypeProvider typeProvider,
			CodeTypeReference typeRefLogActContract,
			string logicalName,
			Repository.LogicalActivity logact,
			Repository.LogicalWebMethod logwmeth,
			Repository.LogicalRuleResultEndpoint logresultep,
			Repository.WebMethod webmeth,
			Repository.WebMethod wmCallback,
			Repository.MessageQueueEx msmq,
			ref CodeMemberMethod methInMap,
			ref CodeMemberMethod methOutMap,
			ref CodeMemberMethod methContract,
			CodeTypeReference typeRefMapClass,
			CodeTypeReference typeRefOutput,
			CodeTypeReference typeRefInput,
			List<CodeTypeReference> listTypeRefInputLogAct,
			bool useProxy,
			bool generateConfigLogPhys,
			bool generateConfigSubscribe)
		{
			// get contract method for current webwethod
			if ( currentSvcGenType == ServiceGenerationType.HumanActivityService )
				methContract = getMethodFromCode(codeContracts, typeRefLogActContract.BaseType, "DoHumanActivity");
			else if ( currentSvcGenType == ServiceGenerationType.MessageQueueService )
				methContract = null;
			else
				methContract = getMethodFromCode(codeContracts, typeRefLogActContract.BaseType, webmeth);
			if ( methContract == null &&
				 currentSvcGenType != ServiceGenerationType.MessageQueueService ) {
				throw new Exception(string.Format(
					"The web method '{0}' is not a member of the web service '{1}'. " +
					"Please check the selected web method at the logical method '{2}'.",
					webmeth.Name, typeRefLogActContract.BaseType, logicalName));
			}
			// get mappings
			XsltDocument xsltInLWMtoWM = null;
			XsltDocument xsltInSubscription = null;
			XsltDocument xsltOut = null;
			string inputCodeMapping = null;
			string outputCodeMapping = null;
			if ( logact != null ) {
				xsltInSubscription = logact.InputXslt;
				xsltOut = logact.OutputXslt;
			}
			#region get input and output xslt
			if ( logresultep != null ) {
				if ( useProxy ) {
					if ( logresultep.ProxyInputXSLT != null ) {
						xsltInLWMtoWM = logresultep.ProxyInputXSLT;
					}
					if ( logresultep.ProxyOutputXSLT != null ) {
						xsltOut = logresultep.ProxyOutputXSLT;
					}
				} else {
					if ( logresultep.InputXSLT != null ) {
						xsltInLWMtoWM = logresultep.InputXSLT;
					}
					if ( logresultep.OutputXSLT != null ) {
						xsltOut = logresultep.OutputXSLT;
					}
				}
			} else if ( logwmeth != null ) {
				if ( useProxy ) {
					if ( logwmeth.ProxyInputXSLT != null ) {
						xsltInLWMtoWM = logwmeth.ProxyInputXSLT;
					}
					if ( logwmeth.ProxyOutputXSLT != null ) {
						xsltOut = logwmeth.ProxyOutputXSLT;
					}
				} else {
					if ( logwmeth.ExtendedProperties.UseInputCodeMapping ) {
						inputCodeMapping = logwmeth.ExtendedProperties.InputCodeMapping;
					} else {
						if ( logwmeth.InputXSLT != null ) {
							xsltInLWMtoWM = logwmeth.InputXSLT;
						}
					}
					if ( logwmeth.ExtendedProperties.UseOutputCodeMapping ) {
						outputCodeMapping = logwmeth.ExtendedProperties.OutputCodeMapping;
					} else {
						if ( logwmeth.OutputXSLT != null ) {
							xsltOut = logwmeth.OutputXSLT;
						}
					}
				}
			}
			#endregion

			#region GetCodeInputMappingInput
			List<Type> typesWSInput = new List<Type>();
			List<Type> typesWSOutput = new List<Type>();
			Dictionary<Type, string> dicTypeNamespace = new Dictionary<Type, string>();
			string contractnspace = "Contract";
			string[] inputTypeNames = null;
			if ( webmeth != null ) inputTypeNames = webmeth.InputTypeName.Split(';');
			else inputTypeNames = new string[] { };
			foreach ( string sType in inputTypeNames ) {
				string type = sType.Trim();
				string ns = null;
				if ( type.Contains(":") ) {
					ns = type;
					string[] splitType = type.Split(':');
					type = splitType[splitType.Length - 1];
					ns = ns.Remove(ns.Length - type.Length - 1, type.Length + 1);
				}
				if ( type.StartsWith("System.") ) {
					typesWSInput.Add(Type.GetType(type));
				} else {
					Type t = typeProvider.GetType(type);
					if ( t == null ) t = typeProvider.GetType(type + "Request");
					if ( t == null ) t = typeProvider.GetType(contractnspace + "." + type + "Request");
					typesWSInput.Add(t);
					if ( !string.IsNullOrEmpty(ns) ) {
						dicTypeNamespace.Add(t, ns);
					}
				}
			}
			string[] outputTypeNames = null;
			if ( webmeth != null ) outputTypeNames = webmeth.OutputTypeName.Split(';');
			else if ( msmq != null ) outputTypeNames = new string[] { "System.Object" };
			else outputTypeNames = new string[] { };
			foreach ( string sType in outputTypeNames ) {
				string type = sType.Trim();
				string ns = null;
				if ( type.Contains(":") ) {
					ns = type;
					string[] splitType = type.Split(':');
					type = splitType[splitType.Length - 1];
					ns = ns.Remove(ns.Length - type.Length - 1, type.Length + 1);
				}
				if ( type.StartsWith("System.") ) {
					typesWSOutput.Add(Type.GetType(type));
				} else {
					Type t = typeProvider.GetType(type);
					if ( t == null ) t = typeProvider.GetType(type + "Request");
					if ( t == null ) t = typeProvider.GetType(contractnspace + "." + type + "Request");
					typesWSOutput.Add(t);
					if ( !string.IsNullOrEmpty(ns) ) {
						dicTypeNamespace.Add(t, ns);
					}
				}
			}
			#endregion

			GenerateMappingCode(ctdMapping, ctorMapping, configuration, currentSvcGenType, typeProvider, logicalName,
				ref methInMap, ref methOutMap, methContract, typeRefMapClass,
				typeRefOutput, typeRefInput, listTypeRefInputLogAct, xsltInLWMtoWM,
				xsltInSubscription, xsltOut, generateConfigLogPhys,
				generateConfigSubscribe,
				inputCodeMapping, outputCodeMapping, typesWSInput, logwmeth, typesWSOutput, dicTypeNamespace);

			RefreshTypeProvider(ref typeProvider, ref codeMapping);
		}

		/// <summary>
		/// Generates the mapping code.
		/// </summary>
		/// <param name="ctdMapping">The CTD mapping.</param>
		/// <param name="ctorMapping">The ctor mapping.</param>
		/// <param name="configuration">The configuration.</param>
		/// <param name="currentSvcGenType">Type of the current SVC gen.</param>
		/// <param name="typeProvider">The type provider.</param>
		/// <param name="logicalName">Name of the logical.</param>
		/// <param name="methInMap">The meth in map.</param>
		/// <param name="methOutMap">The meth out map.</param>
		/// <param name="methContract">The meth contract.</param>
		/// <param name="typeRefMapClass">The type ref map class.</param>
		/// <param name="typeRefOutput">The type ref output.</param>
		/// <param name="typeRefInput">The type ref input.</param>
		/// <param name="listTypeRefInputLogAct">The list type ref input log act.</param>
		/// <param name="xsltInLWMtoWM">The XSLT in LW mto WM.</param>
		/// <param name="xsltInSubscription">The XSLT in subscription.</param>
		/// <param name="xsltOut">The XSLT out.</param>
		/// <param name="generateConfigLogPhys">if set to <c>true</c> [generate config log phys].</param>
		/// <param name="isDomainConfigLogPhys">if set to <c>true</c> [is domain config log phys].</param>
		/// <param name="generateConfigSubscribe">if set to <c>true</c> [generate config subscribe].</param>
		/// <param name="isDomainConfigSubscribe">if set to <c>true</c> [is domain config subscribe].</param>
		private void GenerateMappingCode(
			CodeTypeDeclaration ctdMapping, CodeConstructor ctorMapping,
			Configuration configuration,
			ServiceGenerationType currentSvcGenType,
			TypeProvider typeProvider, string logicalName, ref CodeMemberMethod methInMap,
			ref CodeMemberMethod methOutMap, CodeMemberMethod methContract,
			CodeTypeReference typeRefMapClass, CodeTypeReference typeRefOutput,
			CodeTypeReference typeRefInput, List<CodeTypeReference> listTypeRefInputLogAct,
			XsltDocument xsltInLWMtoWM, XsltDocument xsltInSubscription, XsltDocument xsltOut,
			bool generateConfigLogPhys,
			bool generateConfigSubscribe,
			string inputCodeMapping, string outputCodeMapping, List<Type> typesWSInput, LogicalWebMethod lwm, List<Type> typesWSOutput, Dictionary<Type, string> dicTypeNamespace)
		{
			// save xslt as constant strings
			CodeMemberField fieldInSubscription = null;
			CodeMemberField fieldInLWMtoWM = null;
			CodeMemberField fieldOut = null;
			if ( xsltInSubscription != null && xsltInSubscription.DocumentElement != null ) {
				fieldInSubscription = new CodeMemberField(typeof(string), cxsltInputSubscription + logicalName/*webmeth.Name*/);
				fieldInSubscription.InitExpression = new CodePrimitiveExpression(xsltInSubscription.DocumentElement.OuterXml);
				if ( generateConfigSubscribe ) {
					fieldInSubscription.Attributes = MemberAttributes.Private;
					// add value to config
					if ( configuration != null ) {
						configuration.AppSettings.Settings.Add(fieldInSubscription.Name, xsltInSubscription.DocumentElement.OuterXml);
					}
					// add initialization to ctor
					if ( ctorMapping != null ) {
						ctorMapping.Statements.Add(
							new CodeAssignStatement(
								new CodeFieldReferenceExpression(
									new CodeThisReferenceExpression(), fieldInSubscription.Name),
								new CodeArrayIndexerExpression(
									new CodePropertyReferenceExpression(
										new CodeTypeReferenceExpression(typeof(ConfigurationManager)),
										cAppSettings),
									new CodePrimitiveExpression(fieldInSubscription.Name))));
					}
				} else {
					fieldInSubscription.Attributes = MemberAttributes.Private | MemberAttributes.Const;
				}
			}
			if ( xsltInLWMtoWM != null && xsltInLWMtoWM.DocumentElement != null ) {
				fieldInLWMtoWM = new CodeMemberField(typeof(string), cxsltInput + logicalName/*webmeth.Name*/);
				fieldInLWMtoWM.InitExpression = new CodePrimitiveExpression(xsltInLWMtoWM.DocumentElement.OuterXml);
				if ( generateConfigLogPhys ) {
					fieldInLWMtoWM.Attributes = MemberAttributes.Private;
					// add value to config
					if ( configuration != null ) {
						configuration.AppSettings.Settings.Add(fieldInLWMtoWM.Name, xsltInLWMtoWM.DocumentElement.OuterXml);
					}
					// add initialization to ctor
					if ( ctorMapping != null ) {
						ctorMapping.Statements.Add(
								new CodeAssignStatement(
									new CodeFieldReferenceExpression(
										new CodeThisReferenceExpression(), fieldInLWMtoWM.Name),
									new CodeArrayIndexerExpression(
										new CodePropertyReferenceExpression(
											new CodeTypeReferenceExpression(typeof(ConfigurationManager)),
											cAppSettings),
										new CodePrimitiveExpression(fieldInLWMtoWM.Name))));
					}
				} else {
					fieldInLWMtoWM.Attributes = MemberAttributes.Private | MemberAttributes.Const;
				}
			}
			if ( xsltOut != null && xsltOut.DocumentElement != null ) {
				fieldOut = new CodeMemberField(typeof(string), cxsltOutput + logicalName/*webmeth.Name*/);
				fieldOut.InitExpression = new CodePrimitiveExpression(xsltOut.DocumentElement.OuterXml);
				if ( generateConfigLogPhys ) {
					fieldOut.Attributes = MemberAttributes.Private;
					// add value to config
					if ( configuration != null ) {
						configuration.AppSettings.Settings.Add(fieldOut.Name, xsltOut.DocumentElement.OuterXml);
					}
					// add initialization to ctor
					if ( ctorMapping != null ) {
						ctorMapping.Statements.Add(
							new CodeAssignStatement(
								new CodeFieldReferenceExpression(
									new CodeThisReferenceExpression(), fieldOut.Name),
								new CodeArrayIndexerExpression(
									new CodePropertyReferenceExpression(
										new CodeTypeReferenceExpression(typeof(ConfigurationManager)),
										cAppSettings),
									new CodePrimitiveExpression(fieldOut.Name))));
					}
				} else {
					fieldOut.Attributes = MemberAttributes.Private | MemberAttributes.Const;
				}
			}
			if ( inputCodeMapping != null ) {

			}
			if ( outputCodeMapping != null ) {
			}

			// create input mapping method log->phys
			if ( currentSvcGenType == ServiceGenerationType.HumanActivityService ) {
				// for human activities
				methInMap = GenerateMappingMethodForSubscriptions(
					typeProvider, logicalName/*webmeth.Name*/, listTypeRefInputLogAct,
					typeRefMapClass, fieldInSubscription, fieldInLWMtoWM,
					generateConfigLogPhys, generateConfigSubscribe, inputCodeMapping, typesWSInput, lwm, typeRefInput);
				if ( methInMap != null && fieldInSubscription != null ) {
					if ( fieldInSubscription != null ) ctdMapping.Members.AddDistinctByName(fieldInSubscription);
					if ( fieldInLWMtoWM != null ) ctdMapping.Members.AddDistinctByName(fieldInLWMtoWM);
					ctdMapping.Members.AddDistinctByName(methInMap);
				}
				List<string> inputNames = new List<string>();
				if ( lwm.WebMethod != null ) {
					inputNames.AddRange(lwm.WebMethod.InputVariableName.Split(';'));
				}
				methOutMap = GenerateMappingMethod(typeProvider, false, logicalName/*webmeth.Name*/,
					typeRefOutput, typeRefInput, typeRefMapClass, fieldOut, generateConfigLogPhys,
					outputCodeMapping, typesWSInput, inputNames, typesWSOutput, dicTypeNamespace);
				if ( methOutMap != null && fieldOut != null ) {
					ctdMapping.Members.AddDistinctByName(fieldOut);
					ctdMapping.Members.AddDistinctByName(methOutMap);
				}
			} else if ( currentSvcGenType == ServiceGenerationType.MessageQueueService ) {
				methInMap = GenerateMappingMethodForSubscriptions(
					typeProvider, logicalName/*webmeth.Name*/, listTypeRefInputLogAct,
					typeRefMapClass, fieldInSubscription, fieldInLWMtoWM,
					generateConfigLogPhys, generateConfigSubscribe, inputCodeMapping, typesWSInput, lwm, typeRefInput);
				if ( methInMap != null ) {
					if ( fieldInSubscription != null ) ctdMapping.Members.AddDistinctByName(fieldInSubscription);
					if ( fieldInLWMtoWM != null ) ctdMapping.Members.AddDistinctByName(fieldInLWMtoWM);
					ctdMapping.Members.AddDistinctByName(methInMap);
				}

				List<string> inputNames = new List<string>();
				if ( lwm.WebMethod != null ) {
					inputNames.AddRange(lwm.WebMethod.InputVariableName.Split(';'));
				}
				methOutMap = GenerateMappingMethod(typeProvider, false, logicalName/*webmeth.Name*/,
					typeRefOutput, typeRefInput, typeRefMapClass, fieldOut, generateConfigLogPhys,
					outputCodeMapping, typesWSInput, inputNames, typesWSOutput, dicTypeNamespace);
				if ( methOutMap != null ) {
					ctdMapping.Members.AddDistinctByName(methOutMap);
				}
				if ( fieldOut != null ) {
					ctdMapping.Members.AddDistinctByName(fieldOut);
				}
			} else {
				if ( methContract.Parameters.Count > 0 && ( fieldInSubscription != null || inputCodeMapping != null || fieldInLWMtoWM != null ) ) {
					if ( listTypeRefInputLogAct.Count > 0 ) {
						methInMap = GenerateMappingMethodForSubscriptions(
							typeProvider, logicalName/*webmeth.Name*/, listTypeRefInputLogAct,
							typeRefMapClass, fieldInSubscription, fieldInLWMtoWM,
							generateConfigLogPhys, generateConfigSubscribe,
							inputCodeMapping, typesWSInput, lwm, typeRefInput);
						if ( fieldInSubscription != null ) ctdMapping.Members.AddDistinctByName(fieldInSubscription);
						if ( fieldInLWMtoWM != null ) ctdMapping.Members.AddDistinctByName(fieldInLWMtoWM);
						ctdMapping.Members.AddDistinctByName(methInMap);
					} else {
						List<string> inputNames = new List<string>();
						if ( lwm.WebMethod != null ) {
							inputNames.AddRange(lwm.WebMethod.InputVariableName.Split(';'));
						}
						methInMap = GenerateMappingMethod
							(typeProvider, true, logicalName/*webmeth.Name*/, typeRefInput, typeRefOutput,
							typeRefMapClass, fieldInLWMtoWM, generateConfigLogPhys,
							inputCodeMapping, typesWSInput, inputNames, typesWSOutput, dicTypeNamespace);
						if ( fieldInLWMtoWM != null ) ctdMapping.Members.AddDistinctByName(fieldInLWMtoWM);
						ctdMapping.Members.AddDistinctByName(methInMap);
					}
				}

				// create output mapping method phys->log
				if ( methContract.ReturnType != null && ( fieldOut != null || outputCodeMapping != null ) ) {
					//methOutMap = generateMappingMethod(false, meth, typeRefOutput, typeRefMapClass,
					//                                   methContract, fieldOut);

					List<string> inputNames = new List<string>();
					if ( lwm.WebMethod != null ) {
						inputNames.AddRange(lwm.WebMethod.InputVariableName.Split(';'));
					}
					methOutMap = GenerateMappingMethod(typeProvider, false, logicalName/*webmeth.Name*/,
						typeRefOutput, typeRefInput, typeRefMapClass, fieldOut, generateConfigLogPhys,
						outputCodeMapping, typesWSInput, inputNames, typesWSOutput, dicTypeNamespace);
					if ( outputCodeMapping == null ) {
						ctdMapping.Members.AddDistinctByName(fieldOut);
					}
					ctdMapping.Members.AddDistinctByName(methOutMap);
				}
			}
		}

		/// <summary>
		/// Generates the mapping method.
		/// </summary>
		/// <param name="IsInput">if set to <c>true</c> [is input].</param>
		/// <param name="meth">The meth.</param>
		/// <param name="typeRefParameter">The type ref parameter.</param>
		/// <param name="typeRefMapClass">The type ref map class.</param>
		/// <param name="methContract">The meth contract.</param>
		/// <param name="fieldXSLTCode">The field XSLT code.</param>
		/// <returns></returns>
		internal CodeMemberMethod GenerateMappingMethod(
			bool IsInput,
			Repository.WebMethod meth, CodeTypeReference typeRefParameter,
			CodeTypeReference typeRefMapClass, CodeMemberMethod methContract, CodeMemberField fieldXSLTCode)
		{
			CodeMemberMethod methMap = new CodeMemberMethod();
			CodeTypeReference trMappingInput = ( IsInput ? typeRefParameter : methContract.ReturnType );
			CodeTypeReference trMappingOutput = ( IsInput ? methContract.Parameters[0].Type : typeRefParameter );

			methMap.Name = meth.Name + ( IsInput ? "InputMapping" : "OutputMapping" );
			methMap.Attributes = MemberAttributes.Static | MemberAttributes.Public;
			methMap.Parameters.Add(
				new CodeParameterDeclarationExpression(trMappingInput, "input"));
			methMap.ReturnType = trMappingOutput;

			methMap.Statements.Add(
				new CodeVariableDeclarationStatement(
					trMappingOutput,
					"output",
					new CodePrimitiveExpression(null)));
			methMap.Statements.Add(
				new CodeVariableDeclarationStatement(
					typeof(MemoryStream),
					"msInput",
					new CodeObjectCreateExpression(typeof(MemoryStream))));
			methMap.Statements.Add(
				new CodeVariableDeclarationStatement(
					typeof(MemoryStream),
					"msOutput",
					new CodeObjectCreateExpression(typeof(MemoryStream))));

			CodeTryCatchFinallyStatement try1 = new CodeTryCatchFinallyStatement();
			try1.TryStatements.Add(
				new CodeVariableDeclarationStatement(
					typeof(XmlDictionaryWriter),
					"xdwInput",
					new CodeMethodInvokeExpression(
						new CodeTypeReferenceExpression(typeof(XmlDictionaryWriter)),
						"CreateTextWriter",
						new CodeVariableReferenceExpression("msInput"))));
			CodeTryCatchFinallyStatement try2 = new CodeTryCatchFinallyStatement();
			try2.TryStatements.Add(
				new CodeVariableDeclarationStatement(
					typeof(DataContractSerializer),
					"dcsInput",
					new CodeObjectCreateExpression(
						typeof(DataContractSerializer),
						new CodeTypeOfExpression(trMappingInput))));
			try2.TryStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("dcsInput"),
					"WriteObject",
					new CodeVariableReferenceExpression("xdwInput"),
					new CodeArgumentReferenceExpression("input")));
			try2.TryStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xdwInput"),
					"Flush"));
			try2.FinallyStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xdwInput"),
					"Close"));
			try1.TryStatements.Add(try2);
			try1.TryStatements.Add(
				new CodeVariableDeclarationStatement(
					typeof(XslCompiledTransform),
					"xslt",
					new CodeObjectCreateExpression(typeof(XslCompiledTransform))));
			try1.TryStatements.Add(
				new CodeVariableDeclarationStatement(
					typeof(StringReader),
					"srXSLT",
					new CodeObjectCreateExpression(
						typeof(StringReader),
						new CodeFieldReferenceExpression(
							new CodeTypeReferenceExpression(typeRefMapClass),
							fieldXSLTCode.Name))));
			try1.TryStatements.Add(
				new CodeVariableDeclarationStatement(
					typeof(XmlReader),
					"xrXSLT",
					new CodeMethodInvokeExpression(
						new CodeTypeReferenceExpression(typeof(XmlReader)),
						"Create",
						new CodeVariableReferenceExpression("srXSLT"))));
			CodeTryCatchFinallyStatement try3 = new CodeTryCatchFinallyStatement();
			try3.TryStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xslt"),
					"Load",
					new CodeVariableReferenceExpression("xrXSLT")));
			try3.FinallyStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xrXSLT"),
					"Close"));
			try3.FinallyStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("srXSLT"),
					"Close"));
			try1.TryStatements.Add(try3);
			try1.TryStatements.Add(
				new CodeAssignStatement(
					new CodePropertyReferenceExpression(
						new CodeVariableReferenceExpression("msInput"),
						"Position"),
					new CodePrimitiveExpression(0)));
			try1.TryStatements.Add(
				new CodeVariableDeclarationStatement(
					typeof(XmlReader),
					"xrInput",
					new CodeMethodInvokeExpression(
						new CodeTypeReferenceExpression(typeof(XmlReader)),
						"Create",
						new CodeVariableReferenceExpression("msInput"))));
			try1.TryStatements.Add(
				new CodeVariableDeclarationStatement(
					typeof(XmlWriter),
					"xwOutput",
					new CodeMethodInvokeExpression(
						new CodeTypeReferenceExpression(typeof(XmlWriter)),
						"Create",
						new CodeVariableReferenceExpression("msOutput"),
						new CodePropertyReferenceExpression(
							new CodeVariableReferenceExpression("xslt"),
							"OutputSettings"))));
			CodeTryCatchFinallyStatement try4 = new CodeTryCatchFinallyStatement();
			try4.TryStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xslt"),
					"Transform",
					new CodeVariableReferenceExpression("xrInput"),
					new CodeVariableReferenceExpression("xwOutput")));
			try4.TryStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xwOutput"),
					"Flush"));
			try4.FinallyStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xrInput"),
					"Close"));
			try4.FinallyStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xwOutput"),
					"Close"));
			try1.TryStatements.Add(try4);
			try1.TryStatements.Add(
				new CodeAssignStatement(
					new CodePropertyReferenceExpression(
						new CodeVariableReferenceExpression("msOutput"),
						"Position"),
					new CodePrimitiveExpression(0)));
			try1.TryStatements.Add(
				new CodeVariableDeclarationStatement(
					typeof(DataContractSerializer),
					"dcsOutput",
					new CodeObjectCreateExpression(
						typeof(DataContractSerializer),
						new CodeTypeOfExpression(trMappingOutput))));
			try1.TryStatements.Add(
				new CodeVariableDeclarationStatement(
					typeof(object),
					"obj",
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("dcsOutput"),
						"ReadObject",
						new CodeVariableReferenceExpression("msOutput"))));
			try1.TryStatements.Add(
				new CodeConditionStatement(
					new CodeBinaryOperatorExpression(
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("obj"),
							"GetType"),
						CodeBinaryOperatorType.ValueEquality,
						new CodeTypeOfExpression(trMappingOutput)),
					new CodeStatement[] {
										new CodeAssignStatement(
											new CodeVariableReferenceExpression("output"),
											new CodeCastExpression(
												trMappingOutput,
												new CodeVariableReferenceExpression("obj"))),
									},
					new CodeStatement[] {
										new CodeAssignStatement(
											new CodeVariableReferenceExpression("output"),
											new CodePrimitiveExpression(null))
									}));
			try1.FinallyStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("msInput"),
					"Close"));
			try1.FinallyStatements.Add(
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("msOutput"),
					"Close"));

			methMap.Statements.Add(try1);

			methMap.Statements.Add(
				new CodeMethodReturnStatement(
					new CodeVariableReferenceExpression("output")));

			return methMap;
		}

		/// <summary>
		/// Generates the mapping method.
		/// </summary>
		/// <param name="typeProvider">The type provider.</param>
		/// <param name="IsLogicalToPhysical">if set to <c>true</c> [is logical to physical].</param>
		/// <param name="methodName">Name of the method.</param>
		/// <param name="typeRefLogical">The type ref logical.</param>
		/// <param name="typeRefMapClass">The type ref map class.</param>
		/// <param name="fieldXSLTCode">The field XSLT code.</param>
		/// <param name="generateConfigLogPhys">if set to <c>true</c> [generate config log phys].</param>
		/// <param name="isDomainConfigLogPhys">if set to <c>true</c> [is domain config log phys].</param>
		/// <returns></returns>
		internal CodeMemberMethod GenerateMappingMethod(
			TypeProvider typeProvider, bool IsLogicalToPhysical, string methodName,
			CodeTypeReference typeRefLogical, CodeTypeReference typeRefPhysical, CodeTypeReference typeRefMapClass,
			CodeMemberField fieldXSLTCode,
			bool generateConfigLogPhys, string codeMapping, List<Type> typesWSInput, List<string> namesWSInput, List<Type> typesWSOutput, Dictionary<Type, string> dicTypeNamespace)
		{
			if ( fieldXSLTCode == null && codeMapping == null )
				return null;
			CodeMemberMethod methMap = new CodeMemberMethod();
			//default to XmlDocument for non-code mapping
			methMap.Name = methodName + ( IsLogicalToPhysical ? "InputMapping" : "OutputMapping" );
			if ( generateConfigLogPhys ) {
				methMap.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			} else {
				methMap.Attributes = MemberAttributes.Static | MemberAttributes.Public;
			}

			if ( codeMapping != null ) {
				methMap.ReturnType = IsLogicalToPhysical ? new CodeTypeReference(typesWSOutput[0]) : typeRefLogical;
				if ( IsLogicalToPhysical ) {
					methMap.Parameters.Add(
						new CodeParameterDeclarationExpression(
							typeRefLogical, "input0"));
					for ( int i = 0; i < typesWSInput.Count; i++ ) {
						string name = namesWSInput.Count >= i ? namesWSInput[i] : string.Format("input{0}", i);
						CodeParameterDeclarationExpression param =
							new CodeParameterDeclarationExpression(
								typesWSInput[i], name);
						param.Direction = FieldDirection.Out;
						methMap.Parameters.Add(param);

					}
				} else {
					methMap.Parameters.Add(new CodeParameterDeclarationExpression(
						typesWSOutput[0], "input"));
				}
				methMap.Statements.Add(new CodeVariableDeclarationStatement(
					IsLogicalToPhysical ? new CodeTypeReference(typesWSOutput[0]) : typeRefLogical, "result",
					new CodePrimitiveExpression(null)));
				methMap.Statements.Add(new CodeSnippetStatement(codeMapping.AddLeadingTabs(3)));
				methMap.Statements.Add(new CodeMethodReturnStatement(
					new CodeSnippetExpression("result")));
			} else {
				#region XSLT Mapping
				typeRefPhysical = new CodeTypeReference(typeof(XmlDocument));

				methMap.Parameters.Add(
					new CodeParameterDeclarationExpression(
						( IsLogicalToPhysical ? typeRefLogical : typeRefPhysical ),
						"input"));
				methMap.ReturnType = ( IsLogicalToPhysical ? typeRefPhysical : typeRefLogical );

				if ( IsLogicalToPhysical ) {
					methMap.Statements.Add(	// XmlDocument returnVal = null;
						new CodeVariableDeclarationStatement(
							new CodeTypeReference(typeof(XmlDocument)),
							"returnVal",
							new CodePrimitiveExpression(null)));
				} else {
					methMap.Statements.Add(	// LogicalDocType returnVal = null;
						new CodeVariableDeclarationStatement(
							typeRefLogical,
							"returnVal",
							new CodePrimitiveExpression(null)));
				}
				methMap.Statements.Add(	// MemoryStream msInput = new MemoryStream();
					new CodeVariableDeclarationStatement(
						typeof(MemoryStream),
						"msInput",
						new CodeObjectCreateExpression(typeof(MemoryStream))));
				methMap.Statements.Add(	// MemoryStream msOutput = new MemoryStream();
					new CodeVariableDeclarationStatement(
						typeof(MemoryStream),
						"msOutput",
						new CodeObjectCreateExpression(typeof(MemoryStream))));

				// start try1
				CodeTryCatchFinallyStatement try1 = new CodeTryCatchFinallyStatement();
				if ( IsLogicalToPhysical ) {
					Type t = typeProvider.GetType(typeRefLogical.BaseType);
					object[] attibs = t.GetCustomAttributes(typeof(DataContractAttribute), false);
					if ( attibs == null || attibs.Length == 0 ) {
						attibs = t.GetCustomAttributes(typeof(CollectionDataContractAttribute), false);
					}
					if ( attibs == null || attibs.Length == 0 /*this.Workflow.BuildType == WorkflowBuildType.ASMX_IIS*/ ) {
						try1.TryStatements.Add(	// XmlSerializer xs = new XmlSerializer(typeof(LogicalDocType));
							new CodeVariableDeclarationStatement(
								new CodeTypeReference(typeof(XmlSerializer)),
								"xs",
								new CodeObjectCreateExpression(
									new CodeTypeReference(typeof(XmlSerializer)),
									new CodeTypeOfExpression(typeRefLogical))));
						try1.TryStatements.Add(	// xs.Serialize(msInput, input);
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("xs"),
								"Serialize",
								new CodeVariableReferenceExpression("msInput"),
								new CodeVariableReferenceExpression("input")));
					} else {
						try1.TryStatements.Add(	// DataContractSerializer xs = new DataContractSerializer(typeof(LogicalDocType));
							new CodeVariableDeclarationStatement(
								typeof(DataContractSerializer),
								"xs",
								new CodeObjectCreateExpression(
									typeof(DataContractSerializer),
									new CodeTypeOfExpression(typeRefLogical))));
						try1.TryStatements.Add(	//xs.WriteObject(msInput, input);
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("xs"),
								"WriteObject",
								new CodeVariableReferenceExpression("msInput"),
								new CodeVariableReferenceExpression("input")));
					}
				} else {
					try1.TryStatements.Add(	// input.Save(msInput);
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("input"),
							"Save",
							new CodeVariableReferenceExpression("msInput")));
				}

				try1.TryStatements.Add(	// XslCompiledTransform xslt = new XslCompiledTransform();
					new CodeVariableDeclarationStatement(
						typeof(XslCompiledTransform),
						"xslt",
						new CodeObjectCreateExpression(typeof(XslCompiledTransform))));
				CodeTypeReferenceExpression typeRefExpr =
					( fieldXSLTCode.Attributes & MemberAttributes.Const ) == MemberAttributes.Const ?
					new CodeTypeReferenceExpression(typeRefMapClass) : null;
				try1.TryStatements.Add(	// StringReader srXSLT = new StringReader(OpenComposite.Orchestration.Mapping.xsltInputOrOutput);
					new CodeVariableDeclarationStatement(
						typeof(StringReader),
						"srXSLT",
						new CodeObjectCreateExpression(
							typeof(StringReader),
							new CodeFieldReferenceExpression(
								typeRefExpr,
								fieldXSLTCode.Name))));
				try1.TryStatements.Add(	// XmlReader xrXSLT = XmlReader.Create(srXSLT);
					new CodeVariableDeclarationStatement(
						typeof(XmlReader),
						"xrXSLT",
						new CodeMethodInvokeExpression(
							new CodeTypeReferenceExpression(typeof(XmlReader)),
							"Create",
							new CodeVariableReferenceExpression("srXSLT"))));
				// start try2
				CodeTryCatchFinallyStatement try2 = new CodeTryCatchFinallyStatement();
				try2.TryStatements.Add(	// xslt.Load(xrXSLT);
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("xslt"),
						"Load",
						new CodeVariableReferenceExpression("xrXSLT")));
				// finally try2
				try2.FinallyStatements.Add(	// xrXSLT.Close();
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("xrXSLT"),
						"Close"));
				try2.FinallyStatements.Add(	// srXSLT.Close();
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("srXSLT"),
						"Close"));
				// end try2
				try1.TryStatements.Add(try2);
				try1.TryStatements.Add(	// msInput.Position = 0;
					new CodeAssignStatement(
						new CodePropertyReferenceExpression(
							new CodeVariableReferenceExpression("msInput"),
							"Position"),
						new CodePrimitiveExpression(0)));
				try1.TryStatements.Add(	// XmlReader xrInput = XmlReader.Create(msInput);
					new CodeVariableDeclarationStatement(
						typeof(XmlReader),
						"xrInput",
						new CodeMethodInvokeExpression(
							new CodeTypeReferenceExpression(typeof(XmlReader)),
							"Create",
							new CodeVariableReferenceExpression("msInput"))));
				try1.TryStatements.Add(	// XmlWriter xwOutput = XmlWriter.Create(msOutput, xslt.OutputSettings);
					new CodeVariableDeclarationStatement(
						typeof(XmlWriter),
						"xwOutput",
						new CodeMethodInvokeExpression(
							new CodeTypeReferenceExpression(typeof(XmlWriter)),
							"Create",
							new CodeVariableReferenceExpression("msOutput"),
							new CodePropertyReferenceExpression(
								new CodeVariableReferenceExpression("xslt"),
								"OutputSettings"))));
				// start try3
				CodeTryCatchFinallyStatement try3 = new CodeTryCatchFinallyStatement();
				try3.TryStatements.Add(	// xslt.Transform(xrInput, xwOutput);
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("xslt"),
						"Transform",
						new CodeVariableReferenceExpression("xrInput"),
						new CodeVariableReferenceExpression("xwOutput")));
				try3.TryStatements.Add(	// xwOutput.Flush();
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("xwOutput"),
						"Flush"));
				// finally try3
				try3.FinallyStatements.Add(	// xrInput.Close();
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("xrInput"),
						"Close"));
				try3.FinallyStatements.Add(	// xwOutput.Close();
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("xwOutput"),
						"Close"));
				// end try3
				try1.TryStatements.Add(try3);
				try1.TryStatements.Add(	// msOutput.Position = 0;
					new CodeAssignStatement(
						new CodePropertyReferenceExpression(
							new CodeVariableReferenceExpression("msOutput"),
							"Position"),
						new CodePrimitiveExpression(0)));
				if ( IsLogicalToPhysical ) {
					try1.TryStatements.Add(	// returnVal = new XmlDocument();
						new CodeAssignStatement(
							new CodeVariableReferenceExpression("returnVal"),
							new CodeObjectCreateExpression(typeof(XmlDocument))));
					try1.TryStatements.Add( // returnVal.Load(msOutput);
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("returnVal"),
							"Load",
							new CodeVariableReferenceExpression("msOutput")));
				} else {
					Type t = typeProvider.GetType(typeRefLogical.BaseType);
					object[] attibs = t.GetCustomAttributes(typeof(DataContractAttribute), false);
					if ( attibs == null || attibs.Length == 0 ) {
						attibs = t.GetCustomAttributes(typeof(CollectionDataContractAttribute), false);
					}
					if ( attibs == null || attibs.Length == 0 /*this.Workflow.BuildType == WorkflowBuildType.ASMX_IIS*/ ) {
						#region ASMX_IIS
						try1.TryStatements.Add(	// XmlSerializer xsOutput = new XmlSerializer(typeof(LogicalDocType));
							new CodeVariableDeclarationStatement(
								typeof(XmlSerializer),
								"xsOutput",
								new CodeObjectCreateExpression(
									typeof(XmlSerializer),
									new CodeTypeOfExpression(typeRefLogical))));
						try1.TryStatements.Add(	// object obj = xsOutput.Deserialize(msOutput);
							new CodeVariableDeclarationStatement(
								typeof(object),
								"obj",
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("xsOutput"),
									"Deserialize",
									new CodeVariableReferenceExpression("msOutput"))));
						#endregion
					} else {
						#region WCF_IIS
						try1.TryStatements.Add(	// DataContractSerializer xsOutput = new DataContractSerializer(typeof(LogicalDocType));
							new CodeVariableDeclarationStatement(
								typeof(DataContractSerializer),
								"xsOutput",
								new CodeObjectCreateExpression(
									typeof(DataContractSerializer),
									new CodeTypeOfExpression(typeRefLogical))));
						try1.TryStatements.Add(	// object obj = xsOutput.ReadObject(msOutput);
							new CodeVariableDeclarationStatement(
								typeof(object),
								"obj",
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("xsOutput"),
									"ReadObject",
									new CodeVariableReferenceExpression("msOutput"))));
						#endregion
					}
					try1.TryStatements.Add(
						new CodeConditionStatement(
							new CodeBinaryOperatorExpression( // if ( obj.GetType() == typeof(LogicalDocType) )
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("obj"),
									"GetType"),
								CodeBinaryOperatorType.ValueEquality,
								new CodeTypeOfExpression(typeRefLogical)),
							new CodeStatement[] {	// then
							new CodeAssignStatement(	// returnVal = (LogicalDocType)obj;
								new CodeVariableReferenceExpression("returnVal"),
								new CodeCastExpression(
									typeRefLogical,
									new CodeVariableReferenceExpression("obj"))),
						},
							new CodeStatement[] {	// else
							new CodeAssignStatement(	// returnVal = null;	
								new CodeVariableReferenceExpression("returnVal"),
								new CodePrimitiveExpression(null))
						}));
				}

				// try1 finally
				try1.FinallyStatements.Add(	// msInput.Close();
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("msInput"),
						"Close"));
				try1.FinallyStatements.Add(
					new CodeMethodInvokeExpression( // msOutput.Close();
						new CodeVariableReferenceExpression("msOutput"),
						"Close"));

				// end try1
				methMap.Statements.Add(try1);

				methMap.Statements.Add(	// return returnVal;
					new CodeMethodReturnStatement(
						new CodeVariableReferenceExpression("returnVal")));
				#endregion
			}
			return methMap;
		}

		/// <summary>
		/// Generates the mapping method for subscriptions.
		/// </summary>
		/// <param name="typeProvider">The type provider.</param>
		/// <param name="methodName">Name of the method.</param>
		/// <param name="listTypeRefLogical">The list type ref logical.</param>
		/// <param name="typeRefMapClass">The type ref map class.</param>
		/// <param name="fieldXSLTCodeSubscription">The field XSLT code subscription.</param>
		/// <param name="fieldXSLTCode">The field XSLT code.</param>
		/// <param name="generateConfigLogPhys">if set to <c>true</c> [generate config log phys].</param>
		/// <param name="generateConfigSubscribe">if set to <c>true</c> [generate config subscribe].</param>
		/// <param name="codeMapping">The code mapping string.</param>
		/// <param name="typesWSInput">The WS types.</param>
		/// <param name="lwm">The logical web method for input mapping only.</param>
		/// <param name="typeRefInput">The type ref input.</param>
		/// <returns></returns>
		internal CodeMemberMethod GenerateMappingMethodForSubscriptions(
			TypeProvider typeProvider, string methodName,
			List<CodeTypeReference> listTypeRefLogical, CodeTypeReference typeRefMapClass,
			CodeMemberField fieldXSLTCodeSubscription, CodeMemberField fieldXSLTCode,
			bool generateConfigLogPhys, bool generateConfigSubscribe,
			string codeMapping, List<Type> typesWSInput, LogicalWebMethod lwm, CodeTypeReference typeRefInput)
		{
			if ( typeRefMapClass == null ) {
				throw new NullReferenceException("Critical Error: Mapping class missing.");
			}
			if ( fieldXSLTCode == null && string.IsNullOrEmpty(codeMapping) && fieldXSLTCodeSubscription == null &&
				 lwm.IsAssignedTo != LogicalMethodAssignedTo.MessageQueue ) {
				return null;
				//throw new NullReferenceException(string.Format(
				//    "Subscription mapping for method '{0}' does not exists.",
				//    methodName));
			}
			CodeMemberMethod methMap = new CodeMemberMethod();
			CodeTypeReference typeRefPhysical = new CodeTypeReference(typeof(XmlDocument));

			methMap.Name = methodName + "InputMappingPhysical";
			if ( generateConfigLogPhys || generateConfigSubscribe ) {
				methMap.Attributes = MemberAttributes.Public | MemberAttributes.Final;
			} else {
				methMap.Attributes = MemberAttributes.Static | MemberAttributes.Public;
			}
			if ( codeMapping != null ) {
				#region Code Mapping
				methMap.ReturnType = new CodeTypeReference(typeof(bool));
				// add parameters
				for ( int i = 0; i < listTypeRefLogical.Count; i++ ) {
					methMap.Parameters.Add(
						new CodeParameterDeclarationExpression(
							listTypeRefLogical[i],
							string.Format("input{0}_", i)));
				}
				if ( lwm.WebMethod != null ) {
					string[] names = lwm.WebMethod.InputVariableName.Split(';');
					for ( int i = 0; i < typesWSInput.Count; i++ ) {
						int index = methMap.Parameters.Add(
							new CodeParameterDeclarationExpression(
								typesWSInput[i],
								names.Length < i ? string.Format("output{0}", i) : names[i]));
						methMap.Parameters[index].Direction = FieldDirection.Out;
					}
				} else if ( lwm.SendMessageQueue != null ) {
					CodeParameterDeclarationExpression param =
						new CodeParameterDeclarationExpression(typeof(object), "obj");
					param.Direction = FieldDirection.Out;
					int iObj = methMap.Parameters.Add(
						param);
					//if ( lwm.ExtendedProperties.MessageQueueSend && lwm.InputBusinessObject != null ) {
					//    //for ( int i = 0; i < typesWSInput.Count; i++ ) {
					//    //    int index = methMap.Parameters.Add(
					//    //        new CodeParameterDeclarationExpression(
					//    //            typesWSInput[i],
					//    //            names.Length < i ? string.Format("input{0}", i) : names[i]));
					//    //    methMap.Parameters[index].Direction = FieldDirection.Out;
					//    //}
					//    int iObj = methMap.Parameters.Add(
					//        new CodeParameterDeclarationExpression(
					//            typeof(object),
					//            "obj"));
					//    methMap.Parameters[iObj].Direction = FieldDirection.Out;
					//} else if ( !lwm.ExtendedProperties.MessageQueueSend && lwm.OutputBusinessObject != null ) {
					//    methMap.Parameters.Add(
					//        new CodeParameterDeclarationExpression(
					//            typeof(object),
					//            "obj"));
					//    methMap.Parameters[0].Direction = FieldDirection.Out;

					//}
				}
				// add subscription mapping
				#region Subscription Mapping
				if ( lwm.InputBusinessObject != null ) {
					methMap.Statements.Add(	// XmlDocument returnVal = null;
						new CodeVariableDeclarationStatement(
							new CodeTypeReference(typeof(XmlDocument)),
							"returnVal",
							new CodePrimitiveExpression(null)));
					methMap.Statements.Add(	// MemoryStream msInput = new MemoryStream();
						new CodeVariableDeclarationStatement(
							typeof(MemoryStream),
							"msInput",
							new CodeObjectCreateExpression(typeof(MemoryStream))));
					methMap.Statements.Add(	// MemoryStream msSubscribed = new MemoryStream();
						new CodeVariableDeclarationStatement(
							typeof(MemoryStream),
							"msSubscribed",
							new CodeObjectCreateExpression(typeof(MemoryStream))));
					methMap.Statements.Add(	// MemoryStream msOutput = new MemoryStream();
						new CodeVariableDeclarationStatement(
							typeof(MemoryStream),
							"msOutput",
							new CodeObjectCreateExpression(typeof(MemoryStream))));
					for ( int x = 0; x < listTypeRefLogical.Count; x++ ) {
						methMap.Statements.Add(	// MemoryStream msInput0 = new MemoryStream();
							new CodeVariableDeclarationStatement(
								typeof(MemoryStream),
								"msInput" + x.ToString(),
								new CodeObjectCreateExpression(typeof(MemoryStream))));
					}
					// start try1
					CodeTryCatchFinallyStatement try1 = new CodeTryCatchFinallyStatement();
					//if ( this.Workflow.BuildType == WorkflowBuildType.ASMX_IIS ) {
					//    #region ASMX_IIS
					//    try1.TryStatements.Add(	// System.Xml.Serialization.XmlSerializer xs;
					//        new CodeVariableDeclarationStatement(typeof(XmlSerializer), "xs"));
					//    #endregion
					//} else {
					//    #region WCF_IIS
					//    try1.TryStatements.Add(	// System.Runtime.Serialization.DataContractSerializer xs;
					//        new CodeVariableDeclarationStatement(typeof(DataContractSerializer), "xs"));
					//    #endregion
					//}
					try1.TryStatements.Add(	// XmlDocument xdCompound = new XmlDocument();
						new CodeVariableDeclarationStatement(
							typeof(XmlDocument),
							"xdCompound",
							new CodeObjectCreateExpression(typeof(XmlDocument))));
					// xdCompound.AppendChild(xdCompound.CreateElement("tns", "SubscribedDocuments", "http://www.OpenComposite.com/canonical_document");
					try1.TryStatements.Add(
						new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("xdCompound"),
						"AppendChild",
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("xdCompound"),
							"CreateElement",
							new CodePrimitiveExpression("tns"),
							new CodePrimitiveExpression("SubscribedDocuments"),
							new CodePrimitiveExpression(cCanonicalNamespace))));
					int c = 0;
					try1.TryStatements.Add(
						new CodeVariableDeclarationStatement(
							typeof(int),
							"i",
							new CodePrimitiveExpression(0)));
					foreach ( CodeTypeReference typeRef in listTypeRefLogical ) {
						Type t = typeProvider.GetType(typeRef.BaseType);
						object[] attibs = t.GetCustomAttributes(typeof(DataContractAttribute), false);
						if ( attibs == null || attibs.Length == 0 ) {
							attibs = t.GetCustomAttributes(typeof(CollectionDataContractAttribute), false);
						}
						NamedBusinessObject item = typeRef.UserData["BusinessObject"] as NamedBusinessObject;
						BusinessObject bo = item.BusinessObject;
						if ( attibs == null || attibs.Length == 0 ) {
							#region ASMX_IIS
							try1.TryStatements.Add(	// System.Xml.Serialization.XmlSerializer xs;
								new CodeVariableDeclarationStatement(typeof(XmlSerializer), string.Format("xs{0}", c)));
							if ( bo != null && bo.WorkflowFieldID > 0 ) {
								//xs = new System.Xml.Serialization.XmlSerializer(typeof(string), new XmlRootAttibute("BObjName"));
								try1.TryStatements.Add(
									new CodeAssignStatement(
										new CodeVariableReferenceExpression(string.Format("xs{0}", c)),
										new CodeObjectCreateExpression(
											typeof(XmlSerializer),
											new CodeTypeOfExpression(typeRef),
											new CodeObjectCreateExpression(typeof(XmlAttributeOverrides)),
											new CodeArrayCreateExpression(
												new CodeTypeReference(new CodeTypeReference(typeof(Type)), 1), 0),
											new CodeObjectCreateExpression(
												typeof(XmlRootAttribute),
												new CodePrimitiveExpression(bo.Name)),
											new CodePrimitiveExpression(cCanonicalNamespace))));
							} else {
								//xs = new System.Xml.Serialization.XmlSerializer(typeof(OpenComposite.Orchestration.Data.BudgetScore));
								try1.TryStatements.Add(
									new CodeAssignStatement(
										new CodeVariableReferenceExpression(string.Format("xs{0}", c)),
										new CodeObjectCreateExpression(
											typeof(XmlSerializer),
											new CodeTypeOfExpression(typeRef))));
							}
							//xs.Serialize(msInput0, input0);
							try1.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression(string.Format("xs{0}", c)),
									"Serialize",
									new CodeVariableReferenceExpression(string.Format("msInput{0}", c)),
									new CodeVariableReferenceExpression(string.Format("input{0}_", c))));
							#endregion
						} else {
							#region WCF_IIS
							try1.TryStatements.Add(	// System.Runtime.Serialization.DataContractSerializer xs;
								new CodeVariableDeclarationStatement(typeof(DataContractSerializer), string.Format("xs{0}", c)));
							if ( bo != null && bo.WorkflowFieldID > 0 ) {
								//xs = System.Runtime.Serialization.DataContractSerializer(typeof(OpenComposite.Orchestration.Data.BudgetScore));
								try1.TryStatements.Add(
									new CodeAssignStatement(
										new CodeVariableReferenceExpression(string.Format("xs{0}", c)),
										new CodeObjectCreateExpression(
											typeof(DataContractSerializer),
											new CodeTypeOfExpression(typeRef),
											new CodePrimitiveExpression(bo.Name),
											new CodePrimitiveExpression(cCanonicalNamespace))));
							} else {
								//xs = System.Runtime.Serialization.DataContractSerializer(typeof(OpenComposite.Orchestration.Data.BudgetScore));
								try1.TryStatements.Add(
									new CodeAssignStatement(
										new CodeVariableReferenceExpression(string.Format("xs{0}", c)),
										new CodeObjectCreateExpression(
											typeof(DataContractSerializer),
											new CodeTypeOfExpression(typeRef))));
							}
							//xs.WriteObject(msInput0, input0);
							try1.TryStatements.Add(
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression(string.Format("xs{0}", c)),
									"WriteObject",
									new CodeVariableReferenceExpression(string.Format("msInput{0}", c)),
									new CodeVariableReferenceExpression(string.Format("input{0}_", c))));
							#endregion
						}
						//msInput0.Position = 0;
						try1.TryStatements.Add(
							new CodeAssignStatement(
								new CodePropertyReferenceExpression(
									new CodeVariableReferenceExpression(string.Format("msInput{0}", c)),
									"Position"),
								new CodePrimitiveExpression(0)));
						//XmlDocument xd0 = new XmlDocument();
						try1.TryStatements.Add(
							new CodeVariableDeclarationStatement(
								typeof(XmlDocument),
								"xd" + c.ToString(),
								new CodeObjectCreateExpression(typeof(XmlDocument))));
						//xd0.Load(msInput0);
						try1.TryStatements.Add(
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression(string.Format("xd{0}", c)),
								"Load",
								new CodeVariableReferenceExpression(string.Format("msInput{0}", c))));
						try1.TryStatements.Add(
							new CodeVariableDeclarationStatement(
								typeof(XmlElement), string.Format("elem{0}", c),
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("xdCompound"),
								"CreateElement",
								new CodePrimitiveExpression("tns"),
								new CodePrimitiveExpression(item.Name),
								new CodePrimitiveExpression(cCanonicalNamespace))));
						string varName = "i";
						CodeIterationStatement forLoop =
							new CodeIterationStatement(
								new CodeAssignStatement(
									new CodeVariableReferenceExpression(varName),
									new CodePrimitiveExpression(0)),
								new CodeBinaryOperatorExpression(
									new CodeVariableReferenceExpression(varName),
									CodeBinaryOperatorType.LessThan,
									new CodePropertyReferenceExpression(
										new CodePropertyReferenceExpression(
											new CodePropertyReferenceExpression(
												new CodeVariableReferenceExpression(string.Format("xd{0}", c)),
												"DocumentElement"),
											"ChildNodes"),
										"Count")),
								new CodeAssignStatement(
									new CodeVariableReferenceExpression(varName),
									new CodeBinaryOperatorExpression(
										new CodeVariableReferenceExpression(varName),
										CodeBinaryOperatorType.Add,
										new CodePrimitiveExpression(1))));
						forLoop.Statements.Add(
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression(string.Format("elem{0}", c)),
								"AppendChild",
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("xdCompound"),
								"ImportNode",
								new CodeIndexerExpression(
									new CodePropertyReferenceExpression(
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression(string.Format("xd{0}", c)),
											"DocumentElement"),
										"ChildNodes"),
									new CodeVariableReferenceExpression(varName)),
								new CodePrimitiveExpression(true))));
						try1.TryStatements.Add(forLoop);
						// xd0.DocumentElement.Name = "item.Name";
						//try1.TryStatements.Add(
						//    new CodeAssignStatement(
						//        new CodePropertyReferenceExpression(
						//            new CodePropertyReferenceExpression(
						//                new CodeVariableReferenceExpression(string.Format("xd{0}", c)),
						//                "DocumentElement"),
						//            "Name"),
						//        new CodePrimitiveExpression(item.Name)));
						//xdCompound.DocumentElement.AppendChild(xdCompound.ImportNode(xd0.DocumentElement, true));
						try1.TryStatements.Add(
							new CodeMethodInvokeExpression(
								new CodePropertyReferenceExpression(
									new CodeVariableReferenceExpression("xdCompound"),
									"DocumentElement"),
								"AppendChild",
								new CodeVariableReferenceExpression(string.Format("elem{0}", c))
							/*new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("xdCompound"),
								"ImportNode",
								new CodePropertyReferenceExpression(
									new CodeVariableReferenceExpression(string.Format("xd{0}", c)),
									"DocumentElement"),
								new CodePrimitiveExpression(true))*/
																		));
						c++;
					}
					//xdCompound.Save(msInput);
					try1.TryStatements.Add(
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("xdCompound"),
							"Save",
							new CodeVariableReferenceExpression("msInput")));

					try1.TryStatements.Add(	// XslCompiledTransform xslt;
						new CodeVariableDeclarationStatement(
							typeof(XslCompiledTransform),
							"xslt"));
					try1.TryStatements.Add(	// StringReader srXSLT;
						new CodeVariableDeclarationStatement(
							typeof(StringReader),
							"srXSLT"));
					try1.TryStatements.Add(	// XmlReader xrXSLT;
						new CodeVariableDeclarationStatement(
							typeof(XmlReader),
							"xrXSLT"));
					try1.TryStatements.Add(	// XmlReader xrInput;
						new CodeVariableDeclarationStatement(
							typeof(XmlReader),
							"xrInput"));
					try1.TryStatements.Add(	// XmlWriter xwOutput;
						new CodeVariableDeclarationStatement(
							typeof(XmlWriter),
							"xwOutput"));

					if ( fieldXSLTCodeSubscription != null && fieldXSLTCode != null ) {
						createXSLTransform("msInput", "msSubscribed", typeRefMapClass, fieldXSLTCodeSubscription, try1);
						createXSLTransform("msSubscribed", "msOutput", typeRefMapClass, fieldXSLTCode, try1);
					} else if ( fieldXSLTCode != null ) {
						createXSLTransform("msInput", "msOutput", typeRefMapClass, fieldXSLTCode, try1);
					} else if ( fieldXSLTCodeSubscription != null ) {
						createXSLTransform("msInput", "msOutput", typeRefMapClass, fieldXSLTCodeSubscription, try1);
					}

					try1.TryStatements.Add(	// returnVal = new XmlDocument();
						new CodeAssignStatement(
							new CodeVariableReferenceExpression("returnVal"),
							new CodeObjectCreateExpression(typeof(XmlDocument))));
					try1.TryStatements.Add( // returnVal.Load(msOutput);
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("returnVal"),
							"Load",
							new CodeVariableReferenceExpression("msOutput")));

					// try1 finally
					try1.FinallyStatements.Add(	// msInput.Close();
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("msInput"),
							"Close"));
					try1.FinallyStatements.Add(
						new CodeMethodInvokeExpression( // msOutput.Close();
							new CodeVariableReferenceExpression("msOutput"),
							"Close"));

					// end try1
					methMap.Statements.Add(try1);

				#endregion

					if ( typeRefInput != null ) {
						#region Xml -> Input BO
						methMap.Statements.Add(
							new CodeVariableDeclarationStatement(
								typeRefInput, "input0"));
						methMap.Statements.Add(	// MemoryStream msInput = new MemoryStream();
								new CodeVariableDeclarationStatement(
									typeof(MemoryStream),
									"msConvertInput",
									new CodeObjectCreateExpression(typeof(MemoryStream))));
						methMap.Statements.Add( // xdInput.Save(msInput);
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("returnVal"),
								"Save",
								new CodeVariableReferenceExpression("msConvertInput")));
						methMap.Statements.Add(	// msInput.Position = 0;
							new CodeAssignStatement(
								new CodePropertyReferenceExpression(
									new CodeVariableReferenceExpression("msConvertInput"),
									"Position"),
								new CodePrimitiveExpression(0)));
						methMap.Statements.Add(	// object obj0 = null;
							new CodeVariableDeclarationStatement(
								typeof(object),
								"obj0",
								new CodePrimitiveExpression(null)));
						// use DataContractSerializer
						// DataContractSerializer dcsInput0 = new DataContractSerializer(INPUTTYPE);
						methMap.Statements.Add(
							new CodeVariableDeclarationStatement(
								typeof(DataContractSerializer),
								"dcsConvertInput",
								new CodeObjectCreateExpression(
									typeof(DataContractSerializer),
									new CodeTypeOfExpression(typeRefInput.BaseType))));
						methMap.Statements.Add(	// obj0 = dcsInput0.ReadObject(msInput);
							new CodeAssignStatement(
								new CodeVariableReferenceExpression("obj0"),
								new CodeMethodInvokeExpression(
									new CodeVariableReferenceExpression("dcsConvertInput"),
									"ReadObject",
									new CodeVariableReferenceExpression("msConvertInput"))));

						methMap.Statements.Add(
							new CodeConditionStatement(
								new CodeBinaryOperatorExpression(
									new CodeBinaryOperatorExpression(
										new CodeVariableReferenceExpression("obj0"),
										CodeBinaryOperatorType.IdentityInequality,
										new CodePrimitiveExpression(null)),
									CodeBinaryOperatorType.BooleanAnd,
									new CodeBinaryOperatorExpression(
										new CodeMethodInvokeExpression(
											new CodeVariableReferenceExpression("obj0"),
											"GetType"),
										CodeBinaryOperatorType.ValueEquality,
										new CodeTypeOfExpression(typeRefInput.BaseType))),
								new CodeStatement[] {
										new CodeAssignStatement(
											new CodeVariableReferenceExpression("input0" ),
											new CodeCastExpression(
												typeRefInput.BaseType,
												new CodeVariableReferenceExpression("obj0" ))),
									},
								new CodeStatement[] {
										new CodeAssignStatement(
											new CodeVariableReferenceExpression("input0"),
											new CodePrimitiveExpression(null))
									}));
						methMap.Statements.Add(	// msInput.Close();
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("msConvertInput"),
								"Close"));
						#endregion
					}
				}
				// add code
				methMap.Statements.Add(
						new CodeVariableDeclarationStatement(
							typeof(bool), "isOk",
							new CodePrimitiveExpression(true)));
				methMap.Statements.Add(
					new CodeSnippetExpression(codeMapping.AddLeadingTabs(3)));
				methMap.Statements.Add(
					new CodeMethodReturnStatement(
						new CodeVariableReferenceExpression("isOk")));
				#endregion
			} else {
				#region XSLT Mapping
				int i = 0;
				foreach ( CodeTypeReference typeRef in listTypeRefLogical ) {
					methMap.Parameters.Add(
						new CodeParameterDeclarationExpression(
							typeRef,
							"input" + i.ToString()));
					i++;
				}
				methMap.ReturnType = typeRefPhysical;

				methMap.Statements.Add(	// XmlDocument returnVal = null;
					new CodeVariableDeclarationStatement(
						new CodeTypeReference(typeof(XmlDocument)),
						"returnVal",
						new CodePrimitiveExpression(null)));
				methMap.Statements.Add(	// MemoryStream msInput = new MemoryStream();
					new CodeVariableDeclarationStatement(
						typeof(MemoryStream),
						"msInput",
						new CodeObjectCreateExpression(typeof(MemoryStream))));
				methMap.Statements.Add(	// MemoryStream msSubscribed = new MemoryStream();
					new CodeVariableDeclarationStatement(
						typeof(MemoryStream),
						"msSubscribed",
						new CodeObjectCreateExpression(typeof(MemoryStream))));
				methMap.Statements.Add(	// MemoryStream msOutput = new MemoryStream();
					new CodeVariableDeclarationStatement(
						typeof(MemoryStream),
						"msOutput",
						new CodeObjectCreateExpression(typeof(MemoryStream))));
				for ( int x = 0; x < listTypeRefLogical.Count; x++ ) {
					methMap.Statements.Add(	// MemoryStream msInput0 = new MemoryStream();
						new CodeVariableDeclarationStatement(
							typeof(MemoryStream),
							"msInput" + x.ToString(),
							new CodeObjectCreateExpression(typeof(MemoryStream))));
				}
				// start try1
				CodeTryCatchFinallyStatement try1 = new CodeTryCatchFinallyStatement();
				//if ( this.Workflow.BuildType == WorkflowBuildType.ASMX_IIS ) {
				//    #region ASMX_IIS
				//    try1.TryStatements.Add(	// System.Xml.Serialization.XmlSerializer xs;
				//        new CodeVariableDeclarationStatement(typeof(XmlSerializer), "xs"));
				//    #endregion
				//} else {
				//    #region WCF_IIS
				//    try1.TryStatements.Add(	// System.Runtime.Serialization.DataContractSerializer xs;
				//        new CodeVariableDeclarationStatement(typeof(DataContractSerializer), "xs"));
				//    #endregion
				//}
				try1.TryStatements.Add(	// XmlDocument xdCompound = new XmlDocument();
					new CodeVariableDeclarationStatement(
						typeof(XmlDocument),
						"xdCompound",
						new CodeObjectCreateExpression(typeof(XmlDocument))));
				// xdCompound.AppendChild(xdCompound.CreateElement("tns", "SubscribedDocuments", "http://www.OpenComposite.com/canonical_document");
				try1.TryStatements.Add(
					new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xdCompound"),
					"AppendChild",
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("xdCompound"),
						"CreateElement",
						new CodePrimitiveExpression("tns"),
						new CodePrimitiveExpression("SubscribedDocuments"),
						new CodePrimitiveExpression(cCanonicalNamespace))));
				i = 0;
				try1.TryStatements.Add(
					new CodeVariableDeclarationStatement(
						typeof(int),
						"i",
						new CodePrimitiveExpression(0)));

				foreach ( CodeTypeReference typeRef in listTypeRefLogical ) {
					Type t = typeProvider.GetType(typeRef.BaseType);
					object[] attibs = t.GetCustomAttributes(typeof(DataContractAttribute), false);
					if ( attibs == null || attibs.Length == 0 ) {
						attibs = t.GetCustomAttributes(typeof(CollectionDataContractAttribute), false);
					}
					NamedBusinessObject item = typeRef.UserData["BusinessObject"] as NamedBusinessObject;
					BusinessObject bo = item.BusinessObject;
					if ( attibs == null || attibs.Length == 0 ) {
						#region ASMX_IIS
						try1.TryStatements.Add(	// System.Xml.Serialization.XmlSerializer xs;
							new CodeVariableDeclarationStatement(typeof(XmlSerializer), "xs" + i.ToString()));
						if ( bo != null && bo.WorkflowFieldID > 0 ) {
							//xs = new System.Xml.Serialization.XmlSerializer(typeof(string), new XmlRootAttibute("BObjName"));
							try1.TryStatements.Add(
								new CodeAssignStatement(
									new CodeVariableReferenceExpression("xs" + i.ToString()),
									new CodeObjectCreateExpression(
										typeof(XmlSerializer),
										new CodeTypeOfExpression(typeRef),
										new CodeObjectCreateExpression(typeof(XmlAttributeOverrides)),
										new CodeArrayCreateExpression(
											new CodeTypeReference(new CodeTypeReference(typeof(Type)), 1), 0),
										new CodeObjectCreateExpression(
											typeof(XmlRootAttribute),
											new CodePrimitiveExpression(bo.Name)),
										new CodePrimitiveExpression(cCanonicalNamespace))));
						} else {
							//xs = new System.Xml.Serialization.XmlSerializer(typeof(OpenComposite.Orchestration.Data.BudgetScore));
							try1.TryStatements.Add(
								new CodeAssignStatement(
									new CodeVariableReferenceExpression("xs" + i.ToString()),
									new CodeObjectCreateExpression(
										typeof(XmlSerializer),
										new CodeTypeOfExpression(typeRef))));
						}
						//xs.Serialize(msInput0, input0);
						try1.TryStatements.Add(
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("xs" + i.ToString()),
								"Serialize",
								new CodeVariableReferenceExpression("msInput" + i.ToString()),
								new CodeVariableReferenceExpression("input" + i.ToString())));
						#endregion
					} else {
						#region WCF_IIS
						try1.TryStatements.Add(	// System.Runtime.Serialization.DataContractSerializer xs;
							new CodeVariableDeclarationStatement(typeof(DataContractSerializer), "xs" + i.ToString()));
						if ( bo != null && bo.WorkflowFieldID > 0 ) {
							//xs = System.Runtime.Serialization.DataContractSerializer(typeof(OpenComposite.Orchestration.Data.BudgetScore));
							try1.TryStatements.Add(
								new CodeAssignStatement(
									new CodeVariableReferenceExpression("xs" + i.ToString()),
									new CodeObjectCreateExpression(
										typeof(DataContractSerializer),
										new CodeTypeOfExpression(typeRef),
										new CodePrimitiveExpression(bo.Name),
										new CodePrimitiveExpression(cCanonicalNamespace))));
						} else {
							//xs = System.Runtime.Serialization.DataContractSerializer(typeof(OpenComposite.Orchestration.Data.BudgetScore));
							try1.TryStatements.Add(
								new CodeAssignStatement(
									new CodeVariableReferenceExpression("xs" + i.ToString()),
									new CodeObjectCreateExpression(
										typeof(DataContractSerializer),
										new CodeTypeOfExpression(typeRef))));
						}
						//xs.WriteObject(msInput0, input0);
						try1.TryStatements.Add(
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("xs" + i.ToString()),
								"WriteObject",
								new CodeVariableReferenceExpression("msInput" + i.ToString()),
								new CodeVariableReferenceExpression("input" + i.ToString())));
						#endregion
					}
					//msInput0.Position = 0;
					try1.TryStatements.Add(
						new CodeAssignStatement(
							new CodePropertyReferenceExpression(
								new CodeVariableReferenceExpression("msInput" + i.ToString()),
								"Position"),
							new CodePrimitiveExpression(0)));
					//XmlDocument xd0 = new XmlDocument();
					try1.TryStatements.Add(
						new CodeVariableDeclarationStatement(
							typeof(XmlDocument),
							"xd" + i.ToString(),
							new CodeObjectCreateExpression(typeof(XmlDocument))));
					//xd0.Load(msInput0);
					try1.TryStatements.Add(
						new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("xd" + i.ToString()),
							"Load",
							new CodeVariableReferenceExpression("msInput" + i.ToString())));
					try1.TryStatements.Add(
					new CodeVariableDeclarationStatement(
						typeof(XmlElement), string.Format("elem{0}", i),
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("xdCompound"),
						"CreateElement",
						new CodePrimitiveExpression("tns"),
						new CodePrimitiveExpression(item.Name),
						new CodePrimitiveExpression(cCanonicalNamespace))));
					string varName = "i";
					CodeIterationStatement forLoop =
						new CodeIterationStatement(
							new CodeAssignStatement(
								new CodeVariableReferenceExpression(varName),
								new CodePrimitiveExpression(0)),
							new CodeBinaryOperatorExpression(
								new CodeVariableReferenceExpression(varName),
								CodeBinaryOperatorType.LessThan,
								new CodePropertyReferenceExpression(
									new CodePropertyReferenceExpression(
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression(string.Format("xd{0}", i)),
											"DocumentElement"),
										"ChildNodes"),
									"Count")),
							new CodeAssignStatement(
								new CodeVariableReferenceExpression(varName),
								new CodeBinaryOperatorExpression(
									new CodeVariableReferenceExpression(varName),
									CodeBinaryOperatorType.Add,
									new CodePrimitiveExpression(1)))); forLoop.Statements.Add(
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression(string.Format("elem{0}", i)),
								"AppendChild",
							new CodeMethodInvokeExpression(
								new CodeVariableReferenceExpression("xdCompound"),
								"ImportNode",
								new CodeIndexerExpression(
									new CodePropertyReferenceExpression(
										new CodePropertyReferenceExpression(
											new CodeVariableReferenceExpression(string.Format("xd{0}", i)),
											"DocumentElement"),
										"ChildNodes"),
									new CodeVariableReferenceExpression(varName)),
								new CodePrimitiveExpression(true))));
					try1.TryStatements.Add(forLoop);
					// xd0.DocumentElement.Name = "item.Name";
					//try1.TryStatements.Add(
					//    new CodeAssignStatement(
					//        new CodePropertyReferenceExpression(
					//            new CodePropertyReferenceExpression(
					//                new CodeVariableReferenceExpression(string.Format("xd{0}", i)),
					//                "DocumentElement"),
					//            "Name"),
					//        new CodePrimitiveExpression(item.Name)));
					//xdCompound.DocumentElement.AppendChild(xdCompound.ImportNode(xd0.DocumentElement, true));
					//xdCompound.DocumentElement.AppendChild(xdCompound.ImportNode(xd0.DocumentElement, true));
					try1.TryStatements.Add(
						new CodeMethodInvokeExpression(
							new CodePropertyReferenceExpression(
								new CodeVariableReferenceExpression("xdCompound"),
								"DocumentElement"),
							"AppendChild",
							new CodeVariableReferenceExpression(string.Format("elem{0}", i))
						/*new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("xdCompound"),
							"ImportNode",
							new CodePropertyReferenceExpression(
								new CodeVariableReferenceExpression(string.Format("xd{0}", c)),
								"DocumentElement"),
							new CodePrimitiveExpression(true))*/
																	));
					i++;
				}
				//xdCompound.Save(msInput);
				try1.TryStatements.Add(
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("xdCompound"),
						"Save",
						new CodeVariableReferenceExpression("msInput")));

				try1.TryStatements.Add(	// XslCompiledTransform xslt;
					new CodeVariableDeclarationStatement(
						typeof(XslCompiledTransform),
						"xslt"));
				try1.TryStatements.Add(	// StringReader srXSLT;
					new CodeVariableDeclarationStatement(
						typeof(StringReader),
						"srXSLT"));
				try1.TryStatements.Add(	// XmlReader xrXSLT;
					new CodeVariableDeclarationStatement(
						typeof(XmlReader),
						"xrXSLT"));
				try1.TryStatements.Add(	// XmlReader xrInput;
					new CodeVariableDeclarationStatement(
						typeof(XmlReader),
						"xrInput"));
				try1.TryStatements.Add(	// XmlWriter xwOutput;
					new CodeVariableDeclarationStatement(
						typeof(XmlWriter),
						"xwOutput"));

				if ( fieldXSLTCodeSubscription != null && fieldXSLTCode != null ) {
					createXSLTransform("msInput", "msSubscribed", typeRefMapClass, fieldXSLTCodeSubscription, try1);
					createXSLTransform("msSubscribed", "msOutput", typeRefMapClass, fieldXSLTCode, try1);
				} else if ( fieldXSLTCode != null ) {
					createXSLTransform("msInput", "msOutput", typeRefMapClass, fieldXSLTCode, try1);
				} else if ( fieldXSLTCodeSubscription != null ) {
					createXSLTransform("msInput", "msOutput", typeRefMapClass, fieldXSLTCodeSubscription, try1);
				}

				try1.TryStatements.Add(	// returnVal = new XmlDocument();
					new CodeAssignStatement(
						new CodeVariableReferenceExpression("returnVal"),
						new CodeObjectCreateExpression(typeof(XmlDocument))));
				try1.TryStatements.Add( // returnVal.Load(msOutput);
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("returnVal"),
						"Load",
						new CodeVariableReferenceExpression("msOutput")));

				// try1 finally
				try1.FinallyStatements.Add(	// msInput.Close();
					new CodeMethodInvokeExpression(
						new CodeVariableReferenceExpression("msInput"),
						"Close"));
				try1.FinallyStatements.Add(
					new CodeMethodInvokeExpression( // msOutput.Close();
						new CodeVariableReferenceExpression("msOutput"),
						"Close"));

				// end try1
				methMap.Statements.Add(try1);

				methMap.Statements.Add(	// return returnVal;
					new CodeMethodReturnStatement(
						new CodeVariableReferenceExpression("returnVal")));

				#endregion
			}
			return methMap;
		}

		/// <summary>
		/// Creates the XSL transform.
		/// </summary>
		/// <param name="varnameMSInput">The varname MS input.</param>
		/// <param name="varnameMSOutput">The varname MS output.</param>
		/// <param name="typeRefMapClass">The type ref map class.</param>
		/// <param name="fieldXSLTCode">The field XSLT code.</param>
		/// <param name="try1">The try1.</param>
		internal void createXSLTransform(
			string varnameMSInput, string varnameMSOutput,
			CodeTypeReference typeRefMapClass, CodeMemberField fieldXSLTCode,
			CodeTryCatchFinallyStatement try1)
		{
			try1.TryStatements.Add(	// xslt = new XslCompiledTransform();
				new CodeAssignStatement(
					new CodeVariableReferenceExpression("xslt"),
					new CodeObjectCreateExpression(typeof(XslCompiledTransform))));
			CodeTypeReferenceExpression typeRefExpr =
				( fieldXSLTCode.Attributes & MemberAttributes.Const ) == MemberAttributes.Const ?
				new CodeTypeReferenceExpression(typeRefMapClass) : null;
			try1.TryStatements.Add(	// srXSLT = new StringReader(OpenComposite.Orchestration.Mapping.xsltInputOrOutput);
				new CodeAssignStatement(
					new CodeVariableReferenceExpression("srXSLT"),
					new CodeObjectCreateExpression(
						typeof(StringReader),
						new CodeFieldReferenceExpression(
							typeRefExpr,
							fieldXSLTCode.Name))));
			try1.TryStatements.Add(	// xrXSLT = XmlReader.Create(srXSLT);
				new CodeAssignStatement(
					new CodeVariableReferenceExpression("xrXSLT"),
					new CodeMethodInvokeExpression(
						new CodeTypeReferenceExpression(typeof(XmlReader)),
						"Create",
						new CodeVariableReferenceExpression("srXSLT"))));
			// start try2
			CodeTryCatchFinallyStatement try2 = new CodeTryCatchFinallyStatement();
			try2.TryStatements.Add(	// xslt.Load(xrXSLT);
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xslt"),
					"Load",
					new CodeVariableReferenceExpression("xrXSLT")));
			// finally try2
			try2.FinallyStatements.Add(	// xrXSLT.Close();
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xrXSLT"),
					"Close"));
			try2.FinallyStatements.Add(	// srXSLT.Close();
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("srXSLT"),
					"Close"));
			// end try2
			try1.TryStatements.Add(try2);
			try1.TryStatements.Add(	// msInput.Position = 0;
				new CodeAssignStatement(
					new CodePropertyReferenceExpression(
						new CodeVariableReferenceExpression(varnameMSInput),
						"Position"),
					new CodePrimitiveExpression(0)));
			try1.TryStatements.Add(	// xrInput = XmlReader.Create(msInput);
				new CodeAssignStatement(
					new CodeVariableReferenceExpression("xrInput"),
					new CodeMethodInvokeExpression(
						new CodeTypeReferenceExpression(typeof(XmlReader)),
						"Create",
						new CodeVariableReferenceExpression(varnameMSInput))));
			try1.TryStatements.Add(	// xwOutput = XmlWriter.Create(msOutput, xslt.OutputSettings);
				new CodeAssignStatement(
					new CodeVariableReferenceExpression("xwOutput"),
					new CodeMethodInvokeExpression(
						new CodeTypeReferenceExpression(typeof(XmlWriter)),
						"Create",
						new CodeVariableReferenceExpression(varnameMSOutput),
						new CodePropertyReferenceExpression(
							new CodeVariableReferenceExpression("xslt"),
							"OutputSettings"))));
			// start try3
			CodeTryCatchFinallyStatement try3 = new CodeTryCatchFinallyStatement();
			try3.TryStatements.Add(	// xslt.Transform(xrInput, xwOutput);
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xslt"),
					"Transform",
					new CodeVariableReferenceExpression("xrInput"),
					new CodeVariableReferenceExpression("xwOutput")));
			try3.TryStatements.Add(	// xwOutput.Flush();
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xwOutput"),
					"Flush"));
			// finally try3
			try3.FinallyStatements.Add(	// xrInput.Close();
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xrInput"),
					"Close"));
			try3.FinallyStatements.Add(	// xwOutput.Close();
				new CodeMethodInvokeExpression(
					new CodeVariableReferenceExpression("xwOutput"),
					"Close"));
			// end try3
			try1.TryStatements.Add(try3);
			try1.TryStatements.Add(	// msOutput.Position = 0;
				new CodeAssignStatement(
					new CodePropertyReferenceExpression(
						new CodeVariableReferenceExpression(varnameMSOutput),
						"Position"),
					new CodePrimitiveExpression(0)));

		}

		#endregion

		#region Helper Methods
		/// <summary>
		/// Creates the catch clause.
		/// </summary>
		/// <param name="trycatch">The trycatch.</param>
		/// <param name="localvarname">The localvarname.</param>
		/// <param name="message">The message.</param>
		/// <param name="typeException">The type exception.</param>
		internal void CreateCatchClause(CodeTryCatchFinallyStatement trycatch,
			string localvarname, string message, Type typeException)
		{
			CreateCatchClause(trycatch, localvarname, message, typeException, true);
		}
		/// <summary>
		/// Creates the catch clause.
		/// </summary>
		/// <param name="trycatch">The trycatch.</param>
		/// <param name="localvarname">The localvarname.</param>
		/// <param name="message">The message.</param>
		/// <param name="typeException">The type exception.</param>
		internal void CreateCatchClause(CodeTryCatchFinallyStatement trycatch,
			string localvarname, string message, Type typeException, bool abortClient)
		{
			if ( abortClient ) {
				trycatch.CatchClauses.Add(
					new CodeCatchClause(
						localvarname,
						new CodeTypeReference(typeException),
						new CodeExpressionStatement(new CodeMethodInvokeExpression(
							new CodeTypeReferenceExpression(typeof(Trace)),
							"WriteLine",
							new CodeBinaryOperatorExpression(
								new CodePrimitiveExpression(message),
								CodeBinaryOperatorType.Add,
								new CodePropertyReferenceExpression(
									new CodeVariableReferenceExpression(localvarname),
									"Message")))),
						new CodeExpressionStatement(new CodeMethodInvokeExpression(
							new CodeVariableReferenceExpression("client"),
							"Abort")),
						new CodeThrowExceptionStatement(new CodeVariableReferenceExpression(localvarname))));
			} else {
				trycatch.CatchClauses.Add(
					new CodeCatchClause(
						localvarname,
						new CodeTypeReference(typeException),
						new CodeExpressionStatement(new CodeMethodInvokeExpression(
							new CodeTypeReferenceExpression(typeof(Trace)),
							"WriteLine",
							new CodeBinaryOperatorExpression(
								new CodePrimitiveExpression(message),
								CodeBinaryOperatorType.Add,
								new CodePropertyReferenceExpression(
									new CodeVariableReferenceExpression(localvarname),
									"Message")))),
						new CodeThrowExceptionStatement(new CodeVariableReferenceExpression(localvarname))));
			}
		}

		/// <summary>
		/// Refreshes the type provider.
		/// </summary>
		/// <param name="typeProvider">The type provider.</param>
		/// <param name="codeUnit">The code unit.</param>
		internal void RefreshTypeProvider(ref TypeProvider typeProvider, ref CodeCompileUnit codeUnit)
		{
			if ( typeProvider != null ) {
				typeProvider.RemoveCodeCompileUnit(codeUnit);
				typeProvider.AddCodeCompileUnit(codeUnit);
				typeProvider.GetTypes();
				Debug.Assert(( typeProvider.TypeLoadErrors.Count == 0 ));
			}
		}

		/// <summary>
		/// Gets the method from code.
		/// </summary>
		/// <param name="codeUnit">The code unit.</param>
		/// <param name="classfullname">The classfullname.</param>
		/// <param name="methodname">The methodname.</param>
		/// <returns></returns>
		internal CodeMemberMethod getMethodFromCode(CodeCompileUnit codeUnit,
			string classfullname, string methodname)
		{
			foreach ( CodeNamespace codens in codeUnit.Namespaces ) {
				if ( !classfullname.StartsWith(codens.Name) )
					continue;

				foreach ( CodeTypeDeclaration codeclass in codens.Types ) {
					if ( !classfullname.EndsWith(codeclass.Name) )
						continue;

					foreach ( CodeTypeMember member in codeclass.Members ) {
						if ( member is CodeMemberMethod && member.Name == methodname ) {
							return member as CodeMemberMethod;
						}
					}
				}

			}
			return null;
		}
		/// <summary>
		/// Gets the method from code.
		/// </summary>
		/// <param name="codeUnit">The code unit.</param>
		/// <param name="classfullname">The classfullname.</param>
		/// <param name="webmethod">The webmethod.</param>
		/// <returns></returns>
		internal CodeMemberMethod getMethodFromCode(CodeCompileUnit codeUnit,
			string classfullname, WebMethod webmethod)
		{
			string methodname = webmethod.Name;
			string action = webmethod.Action;
			string[] retType = webmethod.OutputTypeName.Split(':');
			string returnname = webmethod.OutputVariableName;
			if ( retType.Length == 1 ) {
				returnname = retType[0];
			} else if ( retType.Length > 1 ) {
				returnname = retType[retType.Length - 1];
			}
			List<CodeMemberMethod> lstMethods = new List<CodeMemberMethod>();
			foreach ( CodeNamespace codens in codeUnit.Namespaces ) {
				if ( !classfullname.StartsWith(codens.Name) )
					continue;

				foreach ( CodeTypeDeclaration codeclass in codens.Types ) {
					if ( !classfullname.EndsWith(codeclass.Name) )
						continue;

					foreach ( CodeTypeMember member in codeclass.Members ) {
						CodeMemberMethod method = member as CodeMemberMethod;
						if ( method == null ) continue;

						if ( member.Name == methodname ) {
							lstMethods.Add(method);
						} else if ( !string.IsNullOrEmpty(action) ) {
							foreach ( CodeAttributeDeclaration attrib in member.CustomAttributes ) {
								if ( attrib.AttributeType.BaseType == typeof(OperationContractAttribute).FullName ) {
									foreach ( CodeAttributeArgument arg in attrib.Arguments ) {
										CodePrimitiveExpression primExpr = arg.Value as CodePrimitiveExpression;
										if ( arg.Name == "Action" && primExpr != null && primExpr.Value != null &&
											 primExpr.Value.Equals(action) ) {
											lstMethods.Add(method);
										}
									}
								} else if ( attrib.AttributeType.BaseType == typeof(SoapDocumentMethodAttribute).FullName ) {
									foreach ( CodeAttributeArgument arg in attrib.Arguments ) {
										CodePrimitiveExpression primExpr = arg.Value as CodePrimitiveExpression;
										if ( arg.Name == "" && primExpr != null && primExpr.Value != null &&
											 primExpr.Value.Equals(action) ) {
											lstMethods.Add(method);
										}
									}
								}
							}
						}
					}
				}

			}
			if ( lstMethods.Count == 1 ) {
				return lstMethods[0];
			} else if ( lstMethods.Count > 1 ) {
				foreach ( CodeMemberMethod m in lstMethods ) {
					if ( m.ReturnType.BaseType.EndsWith(returnname) ) {
						return m;
					}
				}
			}
			return null;
		}


		/// <summary>
		/// Gets the service.
		/// </summary>
		/// <param name="serviceType">Type of the service.</param>
		/// <returns></returns>
		internal object GetService(Type serviceType)
		{
			if ( _serviceProvider != null ) {
				return _serviceProvider.GetService(serviceType);
			} else {
				return null;
			}
		}

		/// <summary>
		/// Compiles the code to an assembly.
		/// </summary>
		/// <param name="outputFilePath">The output file path.</param>
		/// <param name="compilationUnits">The compilation units.</param>
		/// <param name="referencedAssemblies">The referenced assemblies.</param>
		/// <returns>The <see cref="T:System.CodeDom.Compiler.CompilerResults"/>.</returns>
		internal CompilerResults CompileCodeToAssembly(
			string outputFilePath, CodeCompileUnit[] compilationUnits, string[] referencedAssemblies)
		{
			return CSharpGenerator.CompileCodeToAssembly(outputFilePath, compilationUnits, referencedAssemblies);
		}

		/// <summary>
		/// Compiles the code to an assembly.
		/// </summary>
		/// <param name="outputFilePath">The output file path.</param>
		/// <param name="sources">The sources.</param>
		/// <param name="referencedAssemblies">The referenced assemblies.</param>
		/// <returns>The <see cref="T:System.CodeDom.Compiler.CompilerResults"/>.</returns>
		internal CompilerResults CompileCodeToAssembly(
			string outputFilePath, string[] sources, string[] referencedAssemblies)
		{
			return CSharpGenerator.CompileCodeToAssembly(outputFilePath, sources, referencedAssemblies);
		}

		#endregion

		#endregion

		#endregion

		#region Private Members

		#region Fields

		private IServiceProvider _serviceProvider;
		private string xoml = string.Empty;

		#endregion

		#region Methods

		private string getSlnSccSection(Repository.Workflow workflow)
		{
			if ( !workflow.ExtendedProperties.ConnectWithSourceControlOnDeploy ) return "";
			return string.Format(
				"GlobalSection(TeamFoundationVersionControl) = preSolution{3}" +
				  "SccNumberOfProjects = 3{3}" +
				  "SccEnterpriseProvider = {2}{3}" +
				  "SccTeamFoundationServer = {1}{3}" +
				  "SccLocalPath0 = .{3}" +
				  "SccProjectUniqueName1 = {0}.csproj{3}" +
				  "SccLocalPath1 = .{3}" +
				  "SccWebProject2 = true{3}" +
				  "SccProjectUniqueName2 = WCFService{3}" +
				  "SccLocalPath2 = .{3}" +
				  "SccProjectFilePathRelativizedFromConnection2 = WCFService\\{3}" +
				  "SccProjectEnlistmentChoice2 = 2;{3}" +
				"EndGlobalSection{3}",
					workflow.ExtendedProperties.SourceControlServer, workflow.Name,
					"{4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}", Environment.NewLine).AddLeadingTabs(1);
		}

		private string getCsProjSccSection(Repository.Workflow workflow)
		{
			// SAK is the default value (used by TFS)
			if ( !workflow.ExtendedProperties.ConnectWithSourceControlOnDeploy ) return "";
			return string.Format(
				"<SccProjectName>SAK</SccProjectName>{0}" +
				"<SccLocalPath>SAK</SccLocalPath>{0}" +
				"<SccAuxPath>SAK</SccAuxPath>{0}" +
				"<SccProvider>SAK</SccProvider>{0}", Environment.NewLine);
		}

		private void deployASMX_IIS(string sourcepath, string targetpath,
			Repository.Workflow workflow, bool update)
		{
			bool overwrite = !update;
			sourcepath = Path.Combine(sourcepath, "ASMX_IIS");

			// copy and rename template files
			#region create DDLs folder
			string pathdlls = this.createFolder(targetpath, "DLLs");
			#endregion
			#region copy DLLs
			File.Copy(Path.Combine(sourcepath, @"DLLs\OpenComposite.Shared.dll_"),
					  Path.Combine(pathdlls, "OpenComposite.Shared.dll"), true);
			File.Copy(Path.Combine(sourcepath, @"DLLs\OpenComposite.Workflow.dll_"),
					  Path.Combine(pathdlls, "OpenComposite.Workflow.dll"), true);
			#endregion
			#region create Properties folder
			string pathprops = this.createFolder(targetpath, "Properties");
			#endregion
			#region copy properties files
			copyFile(Path.Combine(sourcepath, @"Properties\AssemblyInfo.cs_"),
					  Path.Combine(pathprops, "AssemblyInfo.cs"), overwrite);
			copyFile(Path.Combine(sourcepath, @"Properties\Settings.Designer.cs_"),
					  Path.Combine(pathprops, "Settings.Designer.cs"), overwrite);
			copyFile(Path.Combine(sourcepath, @"Properties\Settings.settings_"),
					  Path.Combine(pathprops, "Settings.settings"), overwrite);
			#endregion
			#region create WebService folder
			string pathws = this.createFolder(targetpath, "WebService");
			#endregion
			#region create App_Code folder
			string pathAppCode = this.createFolder(pathws, "App_Code");
			#endregion
			#region create Bin folder
			string pathBin = this.createFolder(pathws, "Bin");
			#endregion
			#region copy WebService files
			copyFile(Path.Combine(sourcepath, @"WebService\Service.asmx_"),
					  Path.Combine(pathws, "Service.asmx"), overwrite);
			#endregion
			#region set web.config
			// copy web.config
			string webconfigpath = Path.Combine(pathws, "Web.Config");
			copyFile(Path.Combine(sourcepath, @"WebService\Web.Config_"),
					  webconfigpath, overwrite);
			// add configuration to web.config
			string configstring = workflow.ExtendedProperties.ConfigurationString;
			configstring = configstring.Replace(" xmlns=\"http://schemas.microsoft.com/.NetConfiguration/v2.0\"", "");
			XmlDocument xdNewConfig = new XmlDocument();
			xdNewConfig.LoadXml(configstring);
			XmlDocument xdConfig = new XmlDocument();
			xdConfig.Load(webconfigpath);
			// append system.serviceModel
			XmlNode xnOldSvcModel = xdConfig.SelectSingleNode("//system.serviceModel");
			if ( xnOldSvcModel != null ) xnOldSvcModel.ParentNode.RemoveChild(xnOldSvcModel);
			XmlNode xnServiceModel = xdNewConfig.SelectSingleNode("//system.serviceModel");
			if ( xnServiceModel != null ) {
				xdConfig.DocumentElement.AppendChild(xdConfig.ImportNode(xnServiceModel, true));
			}
			// append appSettings
			XmlNode xnAppSettings = xdNewConfig.SelectSingleNode("//appSettings");
			if ( xnAppSettings != null ) {
				if ( xdConfig.DocumentElement["appSettings"] == null ) {
					xdConfig.DocumentElement.AppendChild(xdConfig.CreateElement("appSettings"));
				}
				foreach ( XmlNode xn in xnAppSettings.ChildNodes ) {
					XmlNode xnOld = xdConfig.DocumentElement["appSettings"]
						.SelectSingleNode("./add[@key=\"" + xn.Attributes["key"].Value + "\"]");
					if ( xnOld != null ) xdConfig.DocumentElement["appSettings"].RemoveChild(xnOld);
					xdConfig.DocumentElement["appSettings"].AppendChild(xdConfig.ImportNode(xn, true));
				}
			}
			//xdConfig.Save(webconfigpath);
			XmlWriterSettings settings = new XmlWriterSettings();
			settings.Indent = true;
			settings.IndentChars = "\t";
			settings.NewLineOnAttributes = true;
			using ( XmlWriter xw = XmlTextWriter.Create(webconfigpath, settings) ) {
				xdConfig.WriteTo(xw);
				xw.Flush();
			}
			#endregion
			#region change and copy App_Code files
			string code = "";
			using ( StreamReader sr =
					File.OpenText(Path.Combine(sourcepath, @"WebService\App_Code\Service.cs_")) ) {
				code = sr.ReadToEnd();
			}
			if ( !string.IsNullOrEmpty(code) ) {
				// replace %WF_NAME%
				code = code.Replace("%WF_NAME%", workflow.Name);
				// replace %WF_NAMESPACE%
				code = code.Replace("%WF_NAMESPACE%",
					( string.IsNullOrEmpty(workflow.XmlNamespace) ?
						"http://www.OpenComposite.com/canonical_document" : workflow.XmlNamespace ));
				// replace %WF_FULLNAME%
				code = code.Replace("%WF_FULLNAME%", workflow.ExtendedProperties.FullName);
				// replace %WF_OUTPUTTYPE%
				code = code.Replace("%WF_OUTPUTTYPE%",
					( string.IsNullOrEmpty(workflow.ExtendedProperties.OutputType) ?
						"void" : workflow.ExtendedProperties.OutputType ));
				// replace %WF_STARTMETHODNAME%
				code = code.Replace("%WF_STARTMETHODNAME%", workflow.ExtendedProperties.StartMethodName);
				// replace %WF_INPUTTYPE%
				code = code.Replace("%WF_INPUTTYPE_ARG%",
					string.IsNullOrEmpty(workflow.ExtendedProperties.InputType) ?
						"" : workflow.ExtendedProperties.InputType + " input");
				// replace %WF_INTERFACENAME%
				code = code.Replace("%WF_INTERFACENAME%", workflow.ExtendedProperties.InterfaceName);
				// replace %WF_ORCHESTRATION_NAMESPACE%
				code = code.Replace("%WF_ORCHESTRATION_NAMESPACE%", workflow.ExtendedProperties.NamespaceCode);

				#region %WF_METHOD_CALL%
				string methodcall = "";
				if ( !string.IsNullOrEmpty(workflow.ExtendedProperties.InputType) &&
					 !string.IsNullOrEmpty(workflow.ExtendedProperties.OutputType) ) {
					// input and output exists
					// return (%WF_OUTPUTTYPE%)base.Invoke(
					//	typeof(%WF_INTERFACENAME%), "%WF_STARTMETHODNAME%", true, new object[] { input })[0];
					methodcall = string.Format(
						"return ({0})base.Invoke(typeof({1}), \"{2}\", true, new object[] {{ input }})[0];",
						workflow.ExtendedProperties.OutputType,
						workflow.ExtendedProperties.InterfaceName,
						workflow.ExtendedProperties.StartMethodName);
					// relace %WF_ISONEWAY%
					code = code.Replace("%WF_ISONEWAY%", "");
				} else if ( !string.IsNullOrEmpty(workflow.ExtendedProperties.InputType) ) {
					// no output
					// base.Invoke(typeof(%WF_INTERFACENAME%), "%WF_STARTMETHODNAME%",
					//			   true, new object[] { input });
					methodcall = string.Format(
						"base.Invoke(typeof({0}), \"{1}\", true, new object[] {{ input }});",
						workflow.ExtendedProperties.InterfaceName,
						workflow.ExtendedProperties.StartMethodName);
					// relace %WF_ISONEWAY%
					code = code.Replace("%WF_ISONEWAY%", ", OneWay = true");
				} else if ( !string.IsNullOrEmpty(workflow.ExtendedProperties.OutputType) ) {
					// no input
					// return (%WF_OUTPUTTYPE%)base.Invoke(
					//	typeof(%WF_INTERFACENAME%), "%WF_STARTMETHODNAME%", true, null)[0];
					methodcall = string.Format(
						"return ({0})base.Invoke(typeof({1}), \"{2}\", true, null)[0];",
						workflow.ExtendedProperties.OutputType,
						workflow.ExtendedProperties.InterfaceName,
						workflow.ExtendedProperties.StartMethodName);
				} else {
					// no input and output
					// base.Invoke(typeof(%WF_INTERFACENAME%), "%WF_STARTMETHODNAME%", true, null);
					methodcall = string.Format(
						"base.Invoke(typeof({0}), \"{1}\", true, null);",
						workflow.ExtendedProperties.InterfaceName,
						workflow.ExtendedProperties.StartMethodName);
					// relace %WF_ISONEWAY%
					code = code.Replace("%WF_ISONEWAY%", "");
				}
				code = code.Replace("%WF_METHOD_CALL%", methodcall);
				#endregion

				File.WriteAllText(Path.Combine(pathAppCode, "Service.cs"), code);
			} else {
				// TODO: show error?
			}
			#endregion
			if ( overwrite || !File.Exists(Path.Combine(targetpath, workflow.Name + ".csproj")) ) {
				#region change and copy vsproj file
				using ( StreamReader sr =
						File.OpenText(Path.Combine(sourcepath, @"Orchestration1.csproj_")) ) {
					code = sr.ReadToEnd();
				}
				if ( !string.IsNullOrEmpty(code) ) {
					// replace %WF_NAME%
					code = code.Replace("%WF_NAME%", workflow.Name);
					File.WriteAllText(Path.Combine(targetpath, workflow.Name + ".csproj"), code);
				} else {
					// TODO: ERROR
				}
				#endregion
			}
			if ( update || !File.Exists(Path.Combine(targetpath, workflow.Name + ".sln")) ) {
				#region change and copy solution file
				using ( StreamReader sr =
						File.OpenText(Path.Combine(sourcepath, @"Orchestration1.sln_")) ) {
					code = sr.ReadToEnd();
				}
				if ( !string.IsNullOrEmpty(code) ) {
					// replace %WF_NAME%
					code = code.Replace("%WF_NAME%", workflow.Name);
					// replace %SCC_SECTION%
					string section = getSlnSccSection(workflow);
					code = code.Replace("%SCC_SECTION%", section);
					File.WriteAllText(Path.Combine(targetpath, workflow.Name + ".sln"), code);
				} else {
					// TODO: ERROR
				}
				#endregion
			}
			// load project file
			string projFile = Path.Combine(targetpath, workflow.Name + ".csproj");
			XmlDocument xdProject = new XmlDocument();
			xdProject.Load(projFile);

			#region save generated files
			saveFiles(xdProject, targetpath, workflow);
			#endregion
		}
		private void deployWCF_IIS(string sourcepath, string targetpath,
			Repository.Workflow workflow, bool update)
		{
			bool overwrite = !update;
			sourcepath = Path.Combine(sourcepath, "WCF_IIS");
			// copy and rename template files
			#region create DDLs folder
			string pathdlls = this.createFolder(targetpath, "DLLs");
			#endregion
			#region copy DLLs
			File.Copy(Path.Combine(sourcepath, @"DLLs\OpenComposite.Shared.dll_"),
					  Path.Combine(pathdlls, "OpenComposite.Shared.dll"), true);
			File.Copy(Path.Combine(sourcepath, @"DLLs\OpenComposite.Workflow.dll_"),
					  Path.Combine(pathdlls, "OpenComposite.Workflow.dll"), true);
			#endregion
			#region create Properties folder
			string pathprops = this.createFolder(targetpath, "Properties");
			#endregion
			#region copy properties files
			copyFile(Path.Combine(sourcepath, @"Properties\AssemblyInfo.cs_"),
					  Path.Combine(pathprops, "AssemblyInfo.cs"), overwrite);
			copyFile(Path.Combine(sourcepath, @"Properties\Settings.Designer.cs_"),
					  Path.Combine(pathprops, "Settings.Designer.cs"), overwrite);
			copyFile(Path.Combine(sourcepath, @"Properties\Settings.settings_"),
					  Path.Combine(pathprops, "Settings.settings"), overwrite);
			#endregion
			#region create WebService folder
			string pathws = this.createFolder(targetpath, "WCFService");
			#endregion
			#region create App_Code folder
			string pathAppCode = this.createFolder(pathws, "App_Code");
			#endregion
			#region create Bin folder
			string pathBin = this.createFolder(pathws, "Bin");
			#endregion
			// copy WebService files
			#region Service.svc
			string service = "";
			using ( StreamReader sr =
					File.OpenText(Path.Combine(sourcepath, @"WCFService\Service.svc_")) ) {
				service = sr.ReadToEnd();
			}
			if ( !string.IsNullOrEmpty(service) ) {
				// replace %SERVICENAME%
				service = service.Replace("%SERVICENAME%",
					string.Format("{0}Service", workflow.Name));
			}
			File.WriteAllText(Path.Combine(pathws, "Service.svc"), service);
			#endregion

			#region Web.Config
			string config = "";
			using ( StreamReader sr =
					File.OpenText(Path.Combine(sourcepath, @"WCFService\Web.Config_")) ) {
				config = sr.ReadToEnd();
			}
			if ( !string.IsNullOrEmpty(config) ) {
				// replace %SERVICE_NAME%
				config = config.Replace("%SERVICE_NAME%",
					string.Format("{0}Service", workflow.Name));
				// replace %SERVICE_FULLNAME%
				config = config.Replace("%SERVICE_FULLNAME%",
					string.Format("{0}Service", workflow.Name));
				// replace %INTERFACE_FULLNAME%
				config = config.Replace("%INTERFACE_FULLNAME%",
					string.Format("{0}.{1}", workflow.ExtendedProperties.NamespaceCode,
											 workflow.ExtendedProperties.InterfaceName));
				// replace %NAMESPACE%
				config = config.Replace("%NAMESPACE%",
					( string.IsNullOrEmpty(workflow.XmlNamespace) ?
						"http://www.OpenComposite.com/canonical_document" : workflow.XmlNamespace ));

				config = config.Replace("%RECEIVE_TIMEOUT%",
					workflow.ExtendedProperties.HasHumanActivity ? "24.00:00:00" : "00:10:00");
				config = config.Replace("%SEND_TIMEOUT%",
					workflow.ExtendedProperties.HasHumanActivity ? "24.00:00:00" : "00:10:00");
				if ( workflow.ExtendedProperties.UseBasicHttpBinding ) {
					config = config.Replace("%ENDPOINT_BINDING%",
						"binding=\"basicHttpBinding\"");
				} else {
					config = config.Replace("%ENDPOINT_BINDING%",
						"binding=\"wsDualHttpBinding\" bindingConfiguration=\"bindConfig\"");
				}
				string trackingPersistence = "";
				if ( workflow.ExtendedProperties.UseDefaultPersistence ) {
					trackingPersistence += string.Format("<add type=\"System.Workflow.Runtime.Hosting.SqlWorkflowPersistenceService, System.Workflow.Runtime, Version=3.0.00000.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" " +
															"connectionString=\"{0}\" />", workflow.ExtendedProperties.DefaultPersistenceConnection);
				}
				if ( workflow.ExtendedProperties.UseDefaultTracking ) {
					trackingPersistence += string.Format("<add type=\"System.Workflow.Runtime.Tracking.SqlTrackingService, System.Workflow.Runtime, Version=3.0.00000.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" " +
															"connectionString=\"{0}\" />", workflow.ExtendedProperties.DefaultTrackingConnection);
				}
				config = config.Replace("%TRACKING_PERSISTENCE%", trackingPersistence);
			}
			// write web.config
			string webconfigpath = Path.Combine(pathws, "Web.Config");
			File.WriteAllText(webconfigpath, config);
			// add configuration to web.config
			string configstring = workflow.ExtendedProperties.ConfigurationString;
			configstring = configstring.Replace(" xmlns=\"http://schemas.microsoft.com/.NetConfiguration/v2.0\"", "");
			XmlDocument xdNewConfig = new XmlDocument();
			xdNewConfig.LoadXml(configstring);
			XmlDocument xdConfig = new XmlDocument();
			xdConfig.Load(webconfigpath);
			// append system.serviceModel
			XmlNode xnOldSvcModel = xdConfig.SelectSingleNode("//system.serviceModel");
			if ( xnOldSvcModel != null ) {
				XmlElement xeOldBindungs = xnOldSvcModel["bindings"];
				XmlElement xeOldClient = xnOldSvcModel["client"];
				if ( xeOldBindungs != null ) {
					List<XmlNode> removable = new List<XmlNode>();
					foreach ( XmlNode xnBChild in xeOldBindungs.ChildNodes ) {
						if ( xnBChild.SelectSingleNode("./binding[@name='bindConfig']") == null ) {
							removable.Add(xnBChild);
						}
					}
					foreach ( XmlNode xnRemove in removable ) {
						xeOldBindungs.RemoveChild(xnRemove);
					}
					//xnOldSvcModel.RemoveChild(xeOldBindungs);
				}
				if ( xeOldClient != null ) xnOldSvcModel.RemoveChild(xeOldClient);
				//xnOldSvcModel.ParentNode.RemoveChild(xnOldSvcModel);
			}
			XmlNode xnServiceModel = xdNewConfig.SelectSingleNode("//system.serviceModel");
			if ( xnServiceModel != null ) {
				if ( xnOldSvcModel == null ) {
					xnOldSvcModel = xdConfig.DocumentElement.AppendChild(xdConfig.CreateElement("system.serviceModel"));
				}
				if ( xnServiceModel["bindings"] != null ) {
					if ( xnOldSvcModel["bindings"] == null ) {
						xnOldSvcModel.AppendChild(xdConfig.ImportNode(xnServiceModel["bindings"], true));
					} else {
						foreach ( XmlNode xn in xnServiceModel["bindings"].ChildNodes ) {
							XmlNode xnImported = xdConfig.ImportNode(xn, true);
							addTimeoutsToBindings(xdConfig, xnImported);
							xnOldSvcModel["bindings"].AppendChild(xnImported);
						}
					}
				}
				if ( xnServiceModel["client"] != null ) {
					xnOldSvcModel.AppendChild(xdConfig.ImportNode(xnServiceModel["client"], true));
				}
				//xdConfig.DocumentElement.AppendChild(xdConfig.ImportNode(xnServiceModel, true));
			}
			// append appSettings
			XmlNode xnAppSettings = xdNewConfig.SelectSingleNode("//appSettings");
			if ( xnAppSettings != null ) {
				if ( xdConfig.DocumentElement["appSettings"] == null ) {
					xdConfig.DocumentElement.AppendChild(xdConfig.CreateElement("appSettings"));
				}
				foreach ( XmlNode xn in xnAppSettings.ChildNodes ) {
					XmlNode xnOld = xdConfig.DocumentElement["appSettings"]
						.SelectSingleNode("./add[@key=\"" + xn.Attributes["key"].Value + "\"]");
					if ( xnOld != null ) xdConfig.DocumentElement["appSettings"].RemoveChild(xnOld);
					xdConfig.DocumentElement["appSettings"].AppendChild(xdConfig.ImportNode(xn, true));
				}
			}
			//xdConfig.Save(webconfigpath);
			XmlWriterSettings settings = new XmlWriterSettings();
			settings.Indent = true;
			settings.IndentChars = "\t";
			settings.NewLineOnAttributes = true;
			using ( XmlWriter xw = XmlTextWriter.Create(webconfigpath, settings) ) {
				xdConfig.WriteTo(xw);
				xw.Flush();
			}
			#endregion

			// change and copy App_Code files
			string code = "";
			if ( string.IsNullOrEmpty(workflow.CodeHosting) ) {
				#region change Service.cs
				using ( StreamReader sr =
					File.OpenText(Path.Combine(sourcepath, @"WCFService\App_Code\Service.cs_")) ) {
					code = sr.ReadToEnd();
				}
				if ( !string.IsNullOrEmpty(code) ) {
					if ( workflow.OutputBusinessObjectID > 0 ) {
						code = code.Replace("%WF_WORKFLOW_REPLYEVENT_METHOD%", CodeSnippets.CodeMethodworkflow_ReplyEvent);
						code = code.Replace("%WF_WORKFLOW_REPLYEVENT_BIND%", CodeSnippets.CodeLineBindWorkflow_ReplyEvent);
						code = code.Replace("%WF_DECLARE_RESULT_DICT%", "private Dictionary<Guid, %WF_OUTPUTTYPE%> _results;");
						code = code.Replace("%WF_INIT_RESULT_DICT%", "_results = new Dictionary<Guid, %WF_OUTPUTTYPE%>();");
					} else {
						code = code.Replace("%WF_WORKFLOW_REPLYEVENT_METHOD%", "");
						code = code.Replace("%WF_WORKFLOW_REPLYEVENT_BIND%", "");
						code = code.Replace("%WF_DECLARE_RESULT_DICT%", "");
						code = code.Replace("%WF_INIT_RESULT_DICT%", "");
					}
					// replace %WF_NAME%
					code = code.Replace("%WF_NAME%", workflow.Name);
					// replace %WF_ORCHESTRATION_NAMESPACE%
					code = code.Replace("%WF_ORCHESTRATION_NAMESPACE%", workflow.ExtendedProperties.NamespaceCode);
					// replace %WF_NAMESPACE%
					code = code.Replace("%WF_NAMESPACE%",
						( string.IsNullOrEmpty(workflow.XmlNamespace) ?
							"http://www.OpenComposite.com/canonical_document" : workflow.XmlNamespace ));
					// replace %WF_FULLNAME%
					code = code.Replace("%WF_FULLNAME%", workflow.ExtendedProperties.FullName);
					// replace %WF_OUTPUTTYPE%
					code = code.Replace("%WF_OUTPUTTYPE%",
						( string.IsNullOrEmpty(workflow.ExtendedProperties.OutputType) ?
							"void" : workflow.ExtendedProperties.OutputType ));
					// replace %WF_STARTMETHODNAME%
					code = code.Replace("%WF_STARTMETHODNAME%", workflow.ExtendedProperties.StartMethodName);
					// replace %WF_INPUTTYPE%
					code = code.Replace("%WF_INPUTTYPE_ARG%",
						string.IsNullOrEmpty(workflow.ExtendedProperties.InputType) ?
							"" : workflow.ExtendedProperties.InputType + " input");
					// replace %WF_INTERFACENAME%
					code = code.Replace("%WF_INTERFACENAME%", workflow.ExtendedProperties.InterfaceName);

					#region OLD %WF_METHODSTART_CALL%
					////_localService.Raise % WF_STARTMETHODNAME % Event(workflowInstance.InstanceId, input);
					//string methodstartcall = "";
					//if ( string.IsNullOrEmpty(workflow.ExtendedProperties.InputType) ) {
					//    methodstartcall = string.Format(
					//        "_localService.Raise{0}Event(workflowInstance.InstanceId);",
					//        workflow.ExtendedProperties.StartMethodName);
					//} else {
					//    methodstartcall = string.Format(
					//        "_localService.Raise{0}Event(workflowInstance.InstanceId, input);",
					//        workflow.ExtendedProperties.StartMethodName);
					//}
					//code = code.Replace("%WF_METHODSTART_CALL%", methodstartcall);
					#endregion
					#region %WF_METHODSTART_CALL%
					//    AutoResetEvent waitHandle = new AutoResetEvent(false);
					//    _waitHandles.Add(workflowInstance.InstanceId, waitHandle);

					//    _localService.RaiseProvideAuthorizationEvent(workflowInstance.InstanceId, input);

					//    waitHandle.WaitOne();
					//    _waitHandles.Remove(workflowInstance.InstanceId);

					//    OpenComposite.Orchestration.AuthorizationComposite.Data.AuthorizationResultObject result =
					//_results[workflowInstance.InstanceId];
					//    _results.Remove(workflowInstance.InstanceId);

					//    return result;
					string methodstartcall = "";
					if ( workflow.OutputBusinessObject != null ) {
						methodstartcall += "AutoResetEvent waitHandle = new AutoResetEvent(false);" + Environment.NewLine;
						methodstartcall += "\t\t_waitHandles.Add(workflowInstance.InstanceId, waitHandle);" + Environment.NewLine + Environment.NewLine;
						methodstartcall += "\t\t";
					}
					if ( workflow.InputBusinessObject == null ) {
						methodstartcall += string.Format(
							"_localService.Raise{0}Event(workflowInstance.InstanceId);",
							workflow.ExtendedProperties.StartMethodName);
					} else {
						methodstartcall += string.Format(
							"_localService.Raise{0}Event(workflowInstance.InstanceId, input);",
							workflow.ExtendedProperties.StartMethodName);
					}
					if ( workflow.OutputBusinessObject != null ) {
						methodstartcall += Environment.NewLine + Environment.NewLine;
						methodstartcall += "\t\twaitHandle.WaitOne();" + Environment.NewLine;
						methodstartcall += "\t\t_waitHandles.Remove(workflowInstance.InstanceId);" + Environment.NewLine + Environment.NewLine;
						methodstartcall += "\t\tOpenComposite.Orchestration.AuthorizationComposite.Data.AuthorizationResultObject result =" + Environment.NewLine;
						methodstartcall += "\t\t\t_results[workflowInstance.InstanceId];" + Environment.NewLine;
						methodstartcall += "\t\t_results.Remove(workflowInstance.InstanceId);" + Environment.NewLine + Environment.NewLine;
						methodstartcall += "\t\treturn result;";
					}
					code = code.Replace("%WF_METHODSTART_CALL%", methodstartcall);
					#endregion
					#region %WF_METHODCALLBACK_CALL%
					string methodcallbackcall = "";
					//callback.%WF_STARTMETHODNAME%Callback(e.Output);
					if ( string.IsNullOrEmpty(workflow.ExtendedProperties.OutputType) ) {
						methodcallbackcall = string.Format(
							"callback.{0}Callback();", workflow.ExtendedProperties.StartMethodName);
					} else {
						methodcallbackcall = string.Format(
							"callback.{0}Callback(e.Output);",
							workflow.ExtendedProperties.StartMethodName);
					}
					code = code.Replace("%WF_METHODCALLBACK_CALL%", methodcallbackcall);
					#endregion

					File.WriteAllText(Path.Combine(pathAppCode, "Service.cs"), code);
				} else {
					// TODO: show error?
				}
				#endregion
			} else {
				File.WriteAllText(Path.Combine(pathAppCode, "Service.cs"), workflow.CodeHosting);
			}

			if ( overwrite || !File.Exists(Path.Combine(targetpath, workflow.Name + ".csproj")) ) {
				#region change and copy vsproj file
				using ( StreamReader sr =
						File.OpenText(Path.Combine(sourcepath, @"Orchestration1.csproj_")) ) {
					code = sr.ReadToEnd();
				}
				if ( !string.IsNullOrEmpty(code) ) {
					// replace %WF_NAME%
					code = code.Replace("%WF_NAME%", workflow.Name);
					// replace %SCC_SECTION%

					string section = getCsProjSccSection(workflow);
					code = code.Replace("%SCC_SECTION%", section);
					File.WriteAllText(Path.Combine(targetpath, workflow.Name + ".csproj"), code);
				} else {
					// TODO: ERROR
				}
				#endregion
			}
			if ( overwrite || !File.Exists(Path.Combine(targetpath, workflow.Name + ".sln")) ) {
				#region change and copy sln file
				using ( StreamReader sr =
						File.OpenText(Path.Combine(sourcepath, @"Orchestration1.sln_")) ) {
					code = sr.ReadToEnd();
				}
				if ( !string.IsNullOrEmpty(code) ) {
					// replace %WF_NAME%
					code = code.Replace("%WF_NAME%", workflow.Name);
					// replace %SCC_SECTION%
					string section = getSlnSccSection(workflow);
					code = code.Replace("%SCC_SECTION%", section);
					File.WriteAllText(Path.Combine(targetpath, workflow.Name + ".sln"), code);
				} else {
					// TODO: ERROR
				}
				#endregion
			}

			// load project file
			string projFile = Path.Combine(targetpath, workflow.Name + ".csproj");
			XmlDocument xdProject = new XmlDocument();
			xdProject.Load(projFile);

			#region save generated files
			saveFiles(xdProject, targetpath, workflow);
			#endregion

			#region compile and save business object, rules and endpoint assemblies
			CompilerResults results;

			string nametemplate = workflow.Name + ".{0}";
			string ddlpath = Path.Combine(targetpath, "DLLs");
			string asmBObject = string.Format(nametemplate, "BusinessObjects");
			string asmRules = string.Format(nametemplate, "Rules");
			string asmEPoints = string.Format(nametemplate, "Endpoints");
			string asmLogical = string.Format(nametemplate, "Logical");
			string fileBObject = asmBObject + ".config.dll";
			string fileRules = asmRules + ".config.dll";
			string fileEPoints = asmEPoints + ".config.dll";
			string fileLogical = asmLogical + ".config.dll";
			// business objects
			if ( workflow.IsConfigurable ) {
				results = CompileCodeToAssembly(
					Path.Combine(ddlpath, fileBObject),
					new string[] { workflow.CodeData }, null);
				if ( results.Errors.HasErrors ) {
					throw new Exception(getErrorsString(results));
				}
			}
			// rules
			if ( workflow.IsConfigurable ) {
				results = CompileCodeToAssembly(
					Path.Combine(ddlpath, fileRules),
					new string[] { workflow.CodeRules }, null);
				if ( results.Errors.HasErrors ) {
					throw new Exception(getErrorsString(results));
				}
			}
			// endpoints
			if ( workflow.IsConfigurable ) {
				results = CompileCodeToAssembly(
					Path.Combine(ddlpath, fileEPoints),
					new string[] { workflow.CodeContracts },
					new string[] { typeof(OpenComposite.Base.Structures.RepositoryInformationAttribute).Assembly.Location }
				);
				if ( results.Errors.HasErrors ) {
					throw new Exception(getErrorsString(results));
				}
			}
			// logical
			if ( workflow.IsConfigurable ) {
				results = CompileCodeToAssembly(
					Path.Combine(ddlpath, fileLogical),
					new string[] {
						workflow.CodeOrchestrationInterface,
						workflow.CodeMapping,
						workflow.CodeService
					},
					new string[] {
						Path.Combine(ddlpath, fileBObject),
						Path.Combine(ddlpath, fileEPoints),
						Path.Combine(ddlpath, fileRules)
					}
				);
				if ( results.Errors.HasErrors ) {
					throw new Exception(getErrorsString(results));
				}
			}
			// add references to .csproj
			if ( workflow.IsConfigurable ) {
				addReferenceToProject(xdProject, asmBObject, fileBObject);
			} else {
				removeReferenceFromProject(xdProject, asmBObject);
			}
			if ( workflow.IsConfigurable ) {
				addReferenceToProject(xdProject, asmRules, fileRules);
			} else {
				removeReferenceFromProject(xdProject, asmRules);
			}
			if ( workflow.IsConfigurable ) {
				addReferenceToProject(xdProject, asmEPoints, fileEPoints);
			} else {
				removeReferenceFromProject(xdProject, asmEPoints);
			}
			if ( workflow.IsConfigurable ) {
				addReferenceToProject(xdProject, asmLogical, fileLogical);
			} else {
				removeReferenceFromProject(xdProject, asmLogical);
			}
			// add domain config path
			if ( workflow.ExtendedProperties.ConfigurationLevel == ConfigurationLevel.UtilizeConfiguration &&
				 workflow.DomainConfigPath != null && !string.IsNullOrEmpty(workflow.DomainConfigPath.Path) ) {
				addReferencePathToProject(xdProject, workflow.DomainConfigPath.Path);
			}
			// save config file
			xdProject.Save(projFile);
			#endregion
		}
		private void deployMashup_WinForm(string sourcepath, string targetpath,
			Repository.Workflow workflow, bool update)
		{
			sourcepath = Path.Combine(sourcepath, "Mashup_WinForm");
			// copy and rename template files
			#region create DLLs folder
			string pathdlls = this.createFolder(targetpath, "DLLs");
			#endregion
			#region copy DLLs
			File.Copy(Path.Combine(sourcepath, @"DLLs\OpenComposite.Shared.dll_"),
					  Path.Combine(pathdlls, "OpenComposite.Shared.dll"), true);
			File.Copy(Path.Combine(sourcepath, @"DLLs\OpenComposite.Workflow.dll_"),
					  Path.Combine(pathdlls, "OpenComposite.Workflow.dll"), true);
			#endregion
			bool overwrite = !update;
			#region create Properties folder
			string pathprops = this.createFolder(targetpath, "Properties");
			#endregion
			#region copy properties files
			copyFile(Path.Combine(sourcepath, @"Properties\AssemblyInfo.cs_"),
					  Path.Combine(pathprops, "AssemblyInfo.cs"), overwrite);
			copyFile(Path.Combine(sourcepath, @"Properties\Settings.Designer.cs_"),
					  Path.Combine(pathprops, "Settings.Designer.cs"), overwrite);
			copyFile(Path.Combine(sourcepath, @"Properties\Settings.settings_"),
					  Path.Combine(pathprops, "Settings.settings"), overwrite);
			#endregion
			#region create MashupApplication folder
			string pathApp = this.createFolder(targetpath, "MashupApplication");
			#endregion
			#region copy MashupApplication files
			copyFile(Path.Combine(sourcepath, @"MashupApplication\Form1.cs_"),
					  Path.Combine(pathApp, "Form1.cs"), overwrite);
			copyFile(Path.Combine(sourcepath, @"MashupApplication\Form1.Designer.cs_"),
					  Path.Combine(pathApp, "Form1.Designer.cs"), overwrite);
			#endregion
			#region change MashupApplication files
			// add namespace to Form1.cs
			string file = "";
			using ( FileStream fs = new FileStream(Path.Combine(pathApp, "Form1.cs"), FileMode.Open) ) {
				StreamReader sr = new StreamReader(fs);
				file = sr.ReadToEnd();
			}
			using ( FileStream fs = new FileStream(Path.Combine(pathApp, "Form1.cs"), FileMode.Create) ) {
				file = file.Replace("%WF_ORCHESTRATION_NM%.Data", workflow.Name);
				StreamWriter sw = new StreamWriter(fs);
				sw.Write(file);
				sw.Flush();
			}
			#endregion
			#region Generate Form Mashup Event Handler
			generateFormMashupEventHandler(sourcepath, pathApp, overwrite, workflow);
			#endregion
			if ( overwrite || !File.Exists(Path.Combine(pathApp, "MashupApplication.csproj")) ) {
				#region change and copy csproj file
				string code;
				using ( StreamReader sr =
						File.OpenText(Path.Combine(sourcepath, @"MashupApplication\MashupApplication.csproj_")) ) {
					code = sr.ReadToEnd();
				}
				if ( !string.IsNullOrEmpty(code) ) {
					// replace %WF_NAME%
					code = code.Replace("%WF_NAME%", workflow.Name);
					File.WriteAllText(Path.Combine(pathApp, "MashupApplication.csproj"), code);
				} else {
					// TODO: ERROR
				}
				#endregion
			}
			#region copy Program.cs
			copyFile(Path.Combine(sourcepath, @"MashupApplication\Program.cs_"),
					  Path.Combine(pathApp, "Program.cs"), overwrite);
			#endregion
			#region save app.config
			writeStringToFile(Path.Combine(pathApp, "app.config"), workflow.ExtendedProperties.ConfigurationString);
			#endregion
			#region create Properties folder
			string pathAppProps = this.createFolder(pathApp, "Properties");
			#endregion
			#region copy Properties files
			copyFile(Path.Combine(sourcepath, @"MashupApplication\Properties\AssemblyInfo.cs_"),
					  Path.Combine(pathAppProps, "AssemblyInfo.cs"), overwrite);
			copyFile(Path.Combine(sourcepath, @"MashupApplication\Properties\Settings.Designer.cs_"),
					  Path.Combine(pathAppProps, "Settings.Designer.cs"), overwrite);
			copyFile(Path.Combine(sourcepath, @"MashupApplication\Properties\Settings.settings_"),
					  Path.Combine(pathAppProps, "Settings.settings"), overwrite);
			copyFile(Path.Combine(sourcepath, @"MashupApplication\Properties\Resources.Designer.cs_"),
					  Path.Combine(pathAppProps, "Resources.Designer.cs"), overwrite);
			copyFile(Path.Combine(sourcepath, @"MashupApplication\Properties\Resources.resx_"),
					  Path.Combine(pathAppProps, "Resources.resx"), overwrite);
			#endregion
			if ( overwrite || !File.Exists(Path.Combine(targetpath, workflow.Name + ".csproj")) ) {
				string code;
				#region change and copy vsproj file
				using ( StreamReader sr =
						File.OpenText(Path.Combine(sourcepath, @"Orchestration1.csproj_")) ) {
					code = sr.ReadToEnd();
				}
				if ( !string.IsNullOrEmpty(code) ) {
					// replace %WF_NAME%
					code = code.Replace("%WF_NAME%", workflow.Name);
					File.WriteAllText(Path.Combine(targetpath, workflow.Name + ".csproj"), code);
				} else {
					// TODO: ERROR
				}
				#endregion
			}
			if ( overwrite || !File.Exists(Path.Combine(targetpath, workflow.Name + ".sln")) ) {
				#region change and copy sln file
				string code;
				using ( StreamReader sr =
						File.OpenText(Path.Combine(sourcepath, @"MashUp.sln_")) ) {
					code = sr.ReadToEnd();
				}
				if ( !string.IsNullOrEmpty(code) ) {
					// replace %WF_NAME%
					code = code.Replace("%WF_NAME%", workflow.Name);
					File.WriteAllText(Path.Combine(targetpath, workflow.Name + ".sln"), code);
				} else {
					// TODO: ERROR
				}
				#endregion
			}

			// load project file
			string projFile = Path.Combine(targetpath, workflow.Name + ".csproj");
			XmlDocument xdProject = new XmlDocument();
			xdProject.Load(projFile);

			#region save generated files
			saveFiles(xdProject, targetpath, workflow);
			#endregion

			#region compile and save business object, rules and endpoint assemblies
			CompilerResults results;

			string nametemplate = workflow.Name + ".{0}";
			string ddlpath = Path.Combine(targetpath, "DLLs");
			string asmBObject = string.Format(nametemplate, "BusinessObjects");
			string asmRules = string.Format(nametemplate, "Rules");
			string asmEPoints = string.Format(nametemplate, "Endpoints");
			string asmLogical = string.Format(nametemplate, "Logical");
			string fileBObject = asmBObject + ".config.dll";
			string fileRules = asmRules + ".config.dll";
			string fileEPoints = asmEPoints + ".config.dll";
			string fileLogical = asmLogical + ".config.dll";
			// business objects
			if ( workflow.IsConfigurable ) {
				results = CompileCodeToAssembly(
					Path.Combine(ddlpath, fileBObject),
					new string[] { workflow.CodeData }, null);
				if ( results.Errors.HasErrors ) {
					throw new Exception(getErrorsString(results));
				}
			}
			// rules
			if ( workflow.IsConfigurable ) {
				results = CompileCodeToAssembly(
					Path.Combine(ddlpath, fileRules),
					new string[] { workflow.CodeRules }, null);
				if ( results.Errors.HasErrors ) {
					throw new Exception(getErrorsString(results));
				}
			}
			// endpoints
			if ( workflow.IsConfigurable ) {
				results = CompileCodeToAssembly(
					Path.Combine(ddlpath, fileEPoints),
					new string[] { workflow.CodeContracts },
					new string[] { typeof(OpenComposite.Base.Structures.RepositoryInformationAttribute).Assembly.Location }
				);
				if ( results.Errors.HasErrors ) {
					throw new Exception(getErrorsString(results));
				}
			}
			// logical
			if ( workflow.IsConfigurable ) {
				results = CompileCodeToAssembly(
					Path.Combine(ddlpath, fileLogical),
					new string[] {
						workflow.CodeOrchestrationInterface,
						workflow.CodeMapping,
						workflow.CodeService
					},
					new string[] {
						Path.Combine(ddlpath, fileBObject),
						Path.Combine(ddlpath, fileEPoints),
						Path.Combine(ddlpath, fileRules)
					}
				);
				if ( results.Errors.HasErrors ) {
					throw new Exception(getErrorsString(results));
				}
			}
			// add references to .csproj
			if ( workflow.IsConfigurable ) {
				addReferenceToProject(xdProject, asmBObject, fileBObject);
			} else {
				removeReferenceFromProject(xdProject, asmBObject);
			}
			if ( workflow.IsConfigurable ) {
				addReferenceToProject(xdProject, asmRules, fileRules);
			} else {
				removeReferenceFromProject(xdProject, asmRules);
			}
			if ( workflow.IsConfigurable ) {
				addReferenceToProject(xdProject, asmEPoints, fileEPoints);
			} else {
				removeReferenceFromProject(xdProject, asmEPoints);
			}
			if ( workflow.IsConfigurable ) {
				addReferenceToProject(xdProject, asmLogical, fileLogical);
			} else {
				removeReferenceFromProject(xdProject, asmLogical);
			}
			// add domain config path
			if ( workflow.ExtendedProperties.ConfigurationLevel == ConfigurationLevel.UtilizeConfiguration &&
				 workflow.DomainConfigPath != null && !string.IsNullOrEmpty(workflow.DomainConfigPath.Path) ) {
				addReferencePathToProject(xdProject, workflow.DomainConfigPath.Path);
			}
			// save config file
			xdProject.Save(projFile);
			#endregion
		}
		//#endif

		private void addReferencePathToProject(XmlDocument xdProject, string path)
		{
			XmlNamespaceManager xnsmgr = new XmlNamespaceManager(xdProject.NameTable);
			xnsmgr.AddNamespace("n", cVSProjectFileXmlns);

			//<PropertyGroup>
			//	<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
			//  ...
			//  <ReferencePath>d:\projekte\assemblies\</ReferencePath>
			XmlNode xnExists = xdProject.SelectSingleNode("//n:PropertyGroup/n:ReferencePath[text()='" + path + "']", xnsmgr);
			if ( xnExists != null ) return;

			XmlNode xnConfigPropGroup = xdProject.SelectSingleNode("//n:PropertyGroup/n:Configuration/..", xnsmgr);
			if ( xnConfigPropGroup != null ) {
				XmlElement xeRefPath = xdProject.CreateElement("ReferencePath", cVSProjectFileXmlns);
				xeRefPath.InnerText = path;
				xnConfigPropGroup.AppendChild(xeRefPath);
			}
		}

		private string getErrorsString(CompilerResults results)
		{
			string msg = "";
			foreach ( CompilerError error in results.Errors ) {
				if ( msg.Length > 0 ) msg += Environment.NewLine;
				msg += error.ErrorText;
			}
			return msg;
		}
		private void addReferenceToProject(XmlDocument xdProject, string refName, string fileName)
		{
			XmlNamespaceManager xnsmgr = new XmlNamespaceManager(xdProject.NameTable);
			xnsmgr.AddNamespace("n", cVSProjectFileXmlns);

			XmlNode xnExists = xdProject.SelectSingleNode("//n:ItemGroup/n:Reference[@Include='" + refName + "']", xnsmgr);
			if ( xnExists != null ) return;

			XmlNode xnRefItemGroup = xdProject.SelectSingleNode("//n:ItemGroup/n:Reference/..", xnsmgr);
			XmlElement xeRef = xdProject.CreateElement("Reference", cVSProjectFileXmlns);
			// add include
			XmlAttribute xaInclude = xdProject.CreateAttribute("Include");
			xaInclude.Value = refName;
			xeRef.Attributes.Append(xaInclude);
			// add specific version: false
			XmlElement xeSpecificVersion = xdProject.CreateElement("SpecificVersion", cVSProjectFileXmlns);
			xeSpecificVersion.InnerText = "False";
			xeRef.AppendChild(xeSpecificVersion);
			// add hint path: .\DLLs\...dll
			XmlElement xeHintPath = xdProject.CreateElement("HintPath", cVSProjectFileXmlns);
			xeHintPath.InnerText = ".\\DLLs\\" + fileName;
			xeRef.AppendChild(xeHintPath);
			xnRefItemGroup.AppendChild(xeRef);
		}
		private void removeReferenceFromProject(XmlDocument xdProject, string refName)
		{
			XmlNamespaceManager xnsmgr = new XmlNamespaceManager(xdProject.NameTable);
			xnsmgr.AddNamespace("n", cVSProjectFileXmlns);
			XmlNode xnRef = xdProject.SelectSingleNode("//n:ItemGroup/n:Reference[@Include='" + refName + "']", xnsmgr);
			if ( xnRef != null && xnRef.ParentNode != null ) {
				xnRef.ParentNode.RemoveChild(xnRef);
				xnRef = null;
			}
		}
		private void removeCodeFileFromProject(XmlDocument xdProject, string codefilename)
		{
			//<ItemGroup>
			//  <Compile Include="Contracts.cs" />
			XmlNamespaceManager xnsmgr = new XmlNamespaceManager(xdProject.NameTable);
			xnsmgr.AddNamespace("n", cVSProjectFileXmlns);
			XmlNode xn = xdProject.SelectSingleNode("//n:ItemGroup/n:Compile[@Include='" + codefilename + "']", xnsmgr);
			if ( xn != null && xn.ParentNode != null ) {
				xn.ParentNode.RemoveChild(xn);
				xn = null;
			}
		}
		private void addCodeFileToProject(XmlDocument xdProject, string codefilename)
		{
			XmlNamespaceManager xnsmgr = new XmlNamespaceManager(xdProject.NameTable);
			xnsmgr.AddNamespace("n", cVSProjectFileXmlns);
			XmlNode xnExists = xdProject.SelectSingleNode("//n:ItemGroup/n:Compile[@Include='" + codefilename + "']", xnsmgr);
			if ( xnExists != null ) return;
			XmlNode xnCompileItemGroup = xdProject.SelectSingleNode("//n:ItemGroup/n:Compile/..", xnsmgr);
			if ( xnCompileItemGroup != null ) {
				XmlElement xeCompile = xdProject.CreateElement("Compile", cVSProjectFileXmlns);
				XmlAttribute xaInclude = xdProject.CreateAttribute("Include");
				xaInclude.Value = codefilename;
				xeCompile.Attributes.Append(xaInclude);
				xnCompileItemGroup.AppendChild(xeCompile);
			}
		}

		private void addTimeoutsToBindings(XmlDocument xdConfig, XmlNode xn)
		{
			XmlNodeList xnlBinding = xn.SelectNodes("./binding");
			if ( xnlBinding == null || xnlBinding.Count == 0 ) return;
			foreach ( XmlNode xnBinding in xnlBinding ) {
				addAttributeIfNotExists(xdConfig, xnBinding, "openTimeout", "00:01:00");
				addAttributeIfNotExists(xdConfig, xnBinding, "receiveTimeout", "24.00:00:00");
				addAttributeIfNotExists(xdConfig, xnBinding, "sendTimeout", "24.00:00:00");
				addAttributeIfNotExists(xdConfig, xnBinding, "closeTimeout", "00:01:00");
			}
		}

		private static void addAttributeIfNotExists(
			XmlDocument xdConfig, XmlNode xn, string name, string value)
		{
			if ( xn.Attributes[name] == null ) {
				xn.Attributes.Append(xdConfig.CreateAttribute(name)).Value = value;
			}
		}

		private void generateFormMashupEventHandler(string sourcepath, string pathApp, bool overwrite, OpenComposite.EII.Repository.Workflow workflow)
		{
			#region Constants
			const string END_MASHUPINIT = "#endregion MASHUP PROXY INIT";
			const string END_MASHUPEVENTHANDLER = "#endregion MASHUP PROXY EVENT HANDLER";
			const string END_MASHUPMETHODS = "#endregion MASHUP PROXY METHODS";
			const string PROXY_FIELD_PLACEHOLDER = "%PROXY_FIELD%";
			const string PROXY_FIELD = "private OpenComposite.Orchestration.{0}.{0}Proxy _proxy;";
			const string INIT_PROXY = "_proxy = new OpenComposite.Orchestration.{0}.{0}Proxy();{1}\t\t\t";
			const string REGISTEREVENT =
				"_proxy.{0}Event += new OpenComposite.Orchestration.{2}.{0}EventHandler(_proxy_{0}Event);{1}\t\t\t";
			const string EVENTHANDLER =
				"private void _proxy_{0}Event(object sender, OpenComposite.Orchestration.{2}.{0}EventArgs e){1}" +
				"\t\t{{{1}" +
				"\t\t\tthis.Invoke(new {0}Delegate(this.{0}), e);{1}" +
				"\t\t}}{1}" +
				"\t\tprivate delegate void {0}Delegate(OpenComposite.Orchestration.{2}.{0}EventArgs e);{1}\t\t";
			const string EVENTHANDLER_METHOD =
				"private void {0}(OpenComposite.Orchestration.{2}.{0}EventArgs e){1}" +
				"\t\t{{{1}" +
				"\t\t\t// TODO: add your event handling code here{1}" +
				"\t\t}}{1}\t\t";
			#endregion

			string filepathSource, filepathTarget;
			string code;

			if ( overwrite ) {
				filepathSource = Path.Combine(sourcepath, @"MashupApplication\Form1.Mashup.cs_");
				filepathTarget = Path.Combine(pathApp, "Form1.Mashup.cs");
			} else {
				filepathSource = Path.Combine(pathApp, "Form1.Mashup.cs");
				filepathTarget = Path.Combine(pathApp, "Form1.Mashup.cs");
				if ( !File.Exists(filepathSource) )
					filepathSource = Path.Combine(sourcepath, @"MashupApplication\Form1.Mashup.cs_");
			}

			using ( StreamReader sr = File.OpenText(filepathSource) ) {
				code = sr.ReadToEnd();
			}
			if ( code.Contains(PROXY_FIELD_PLACEHOLDER) ) {
				code = code.Replace(PROXY_FIELD_PLACEHOLDER, string.Format(PROXY_FIELD, workflow.Name));
			}
			int posend = code.IndexOf(END_MASHUPINIT);
			if ( posend == -1 )
				throw new Exception("Form1.Mashup.cs is currupted. Missing '" + END_MASHUPINIT + "'.");

			string initproxy = string.Format(INIT_PROXY, workflow.Name, Environment.NewLine);
			if ( !code.Contains(initproxy.Trim()) ) {
				code = code.Insert(posend, initproxy);
			}
			bool changed = false;

			foreach ( WorkflowMethod wfm in workflow.Interface.Methods ) {
				string regmethevent = string.Format(REGISTEREVENT, wfm.Name, Environment.NewLine, workflow.Name);
				string eventhandler = string.Format(EVENTHANDLER, wfm.Name, Environment.NewLine, workflow.Name);
				string eventmethods = string.Format(EVENTHANDLER_METHOD, wfm.Name, Environment.NewLine, workflow.Name);

				if ( !code.Contains(regmethevent.Trim()) ) {
					posend = code.IndexOf(END_MASHUPINIT);
					if ( posend == -1 )
						throw new Exception("Form1.Mashup.cs is currupted. Missing '" + END_MASHUPINIT + "'.");
					code = code.Insert(posend, regmethevent);

					posend = code.IndexOf(END_MASHUPEVENTHANDLER);
					if ( posend == -1 )
						throw new Exception("Form1.Mashup.cs is currupted. Missing '" + END_MASHUPEVENTHANDLER + "'.");
					code = code.Insert(posend, eventhandler);

					posend = code.IndexOf(END_MASHUPMETHODS);
					if ( posend == -1 )
						throw new Exception("Form1.Mashup.cs is currupted. Missing '" + END_MASHUPMETHODS + "'.");
					code = code.Insert(posend, eventmethods);

					changed = true;
				}
			}
			if ( changed ) {
				posend = code.IndexOf(END_MASHUPINIT);
				if ( posend == -1 )
					throw new Exception("Form1.Mashup.cs is currupted. Missing '" + END_MASHUPINIT + "'.");
				code = code.Insert(posend, Environment.NewLine + "\t\t\t");

				posend = code.IndexOf(END_MASHUPEVENTHANDLER);
				if ( posend == -1 )
					throw new Exception("Form1.Mashup.cs is currupted. Missing '" + END_MASHUPEVENTHANDLER + "'.");
				code = code.Insert(posend, Environment.NewLine + "\t\t");

				posend = code.IndexOf(END_MASHUPMETHODS);
				if ( posend == -1 )
					throw new Exception("Form1.Mashup.cs is currupted. Missing '" + END_MASHUPMETHODS + "'.");
				code = code.Insert(posend, Environment.NewLine + "\t\t");
			}
			File.WriteAllText(filepathTarget, code);
		}

		private void copyFile(string sourceFileName, string destFileName, bool overwriteIfExists)
		{
			if ( overwriteIfExists ) {
				File.Copy(sourceFileName, destFileName, true);
			} else if ( !File.Exists(destFileName) ) {
				File.Copy(sourceFileName, destFileName, false);
			}
		}
		private void saveFiles(XmlDocument xdProject, string path, Repository.Workflow workflow)
		{
			if ( !workflow.IsConfigurable ) {
				writeStringToFile(Path.Combine(path, "Contracts.cs"), workflow.CodeContracts);
				addCodeFileToProject(xdProject, "Contracts.cs");
			} else {
				removeCodeFileFromProject(xdProject, "Contracts.cs");
			}
			if ( !workflow.IsConfigurable ) {
				writeStringToFile(Path.Combine(path, "Data.cs"), workflow.CodeData);
				addCodeFileToProject(xdProject, "Data.cs");
			} else {
				removeCodeFileFromProject(xdProject, "Data.cs");
			}
			writeStringToFile(Path.Combine(path, "IOrchestration.cs"), workflow.CodeInterface);
			writeStringToFile(Path.Combine(path, "LogicalActivities.cs"), workflow.CodeLogicalActivity);
			writeStringToFile(Path.Combine(path, workflow.Name + ".xoml"), workflow.XOML);
			writeStringToFile(Path.Combine(path, workflow.Name + ".xoml.cs"), workflow.CodeBeside);
			writeStringToFile(Path.Combine(path, workflow.Name + ".rules"), workflow.Rules);
			if ( !workflow.IsConfigurable ) {
				writeStringToFile(Path.Combine(path, "Rules.cs"), workflow.CodeRules);
				addCodeFileToProject(xdProject, "Rules.cs");
			} else {
				removeCodeFileFromProject(xdProject, "Rules.cs");
			}
			writeStringToFile(Path.Combine(path, "LocalService.cs"), workflow.CodeLocalService);
			if ( !workflow.IsConfigurable ) {
				writeStringToFile(Path.Combine(path, "ServiceCalls.cs"), workflow.CodeService);
				writeStringToFile(Path.Combine(path, "Mapping.cs"), workflow.CodeMapping);
				writeStringToFile(Path.Combine(path, "I" + workflow.Name + "Orchestration.cs"), workflow.CodeOrchestrationInterface);
				addCodeFileToProject(xdProject, "ServiceCalls.cs");
				addCodeFileToProject(xdProject, "Mapping.cs");
				addCodeFileToProject(xdProject, "I" + workflow.Name + "Orchestration.cs");
			} else {
				removeCodeFileFromProject(xdProject, "ServiceCalls.cs");
				removeCodeFileFromProject(xdProject, "Mapping.cs");
				removeCodeFileFromProject(xdProject, "I" + workflow.Name + "Orchestration.cs");
			}
			writeStringToFile(Path.Combine(path, "app.config"), workflow.ExtendedProperties.ConfigurationString);
		}
		private void writeStringToFile(string filepath, string content)
		{
			using ( StreamWriter sw = new StreamWriter(filepath, false) ) {
				sw.Write(content);
				sw.Flush();
			}
		}
		private string createFolder(string path, string folderName)
		{
			string pathNew = Path.Combine(path, folderName);
			if ( !Directory.Exists(pathNew) )
				Directory.CreateDirectory(pathNew);
			return pathNew;
		}

		private TypeProvider createTypeProvider(IServiceProvider serviceProvider)
		{
			TypeProvider typeProvider = new TypeProvider(serviceProvider);

			typeProvider.AddAssemblyReference(typeof(System.EventHandler).Assembly.Location);
			typeProvider.AddAssemblyReference(typeof(System.ComponentModel.AttributeCollection).Assembly.Location);
			typeProvider.AddAssemblyReference(typeof(System.Workflow.ComponentModel.CompositeActivity).Assembly.Location);
			typeProvider.AddAssemblyReference(typeof(System.Workflow.Activities.SequentialWorkflowActivity).Assembly.Location);
			typeProvider.AddAssemblyReference(typeof(System.Runtime.Serialization.XsdDataContractImporter).Assembly.Location);
			typeProvider.AddAssemblyReference(typeof(System.ServiceModel.EndpointAddress).Assembly.Location);
			typeProvider.AddAssemblyReference(typeof(System.Web.Services.WebService).Assembly.Location);
			typeProvider.AddAssemblyReference(typeof(System.Xml.XmlDocument).Assembly.Location);
			typeProvider.AddAssemblyReference(typeof(OpenComposite.Base.Structures.RepositoryInformationAttribute).Assembly.Location);
			typeProvider.AddAssemblyReference(typeof(OpenComposite.Workflow.LogicalEPActivity).Assembly.Location);

			return typeProvider;
		}

		#endregion

		#endregion
	}

	#region Internal Class: GenerateInfos
	[Serializable]
	internal class GenerateInfos
	{
		internal static string Key = "GenerateInfos";
		internal GenerateInfos()
		{
			UsedCount = 1;
			BObjectID = -1;
		}
		internal int UsedCount;
		internal int BObjectID;
	}
	#endregion
}
